Circular movement in jQuery?

Is there a way to traverse the DOM in a circle? For example, when you get to the end of the list, does it go back to the beginning?

Here is an example that does not work, but hopefully illustrates the effect that I would like to achieve:

<ul> <li></li> <li></li> <li></li> <li class="four"></li> </ul> $('li.four').next().addClass('one'); 
+4
source share
3 answers

Nothing is built in there, but you can trivially write your own method;

 jQuery.fn.nextOrFirst = function (selector) { var next = this.next.apply(this, arguments); if (!next.length) { var siblings = this.siblings(); if (selector) { siblings = siblings.filter(selector); } next = siblings.first(); } return next; }; 

Then use ( http://jsfiddle.net/sszRN/ );

 $('li.four').nextOrFirst().addClass('one'); 
+5
source

I sometimes use

 var $next = $( $(this).next()[0] || $(this).prevAll().addBack()[0] ); 

Yes crazy: D

+2
source

Not quite sure what you are asking for or trying to achieve here, but if you just want to add a class to the first element, you can do it

Turn dom to find the parent

Find the first child of this element - for example,

$('li.four').parent().find(">:first-child").addClass('one');

0
source

Source: https://habr.com/ru/post/1488185/


All Articles