Is there any way to traverse the DOM in a circle? Like, when you get to the end of the list, it loops back around to the beginning?
Here's an example, which does not work, but will hopefully illustrate the effect I would like to achieve:
<ul>
<li></li>
<li></li>
<li></li>
<li class="four"></li>
</ul>
$('li.four').next().addClass('one');
There's nothing built in, 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 like (http://jsfiddle.net/sszRN/);
$('li.four').nextOrFirst().addClass('one');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With