Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular traversing in jQuery?

Tags:

jquery

dom

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');
like image 741
L_Holcombe Avatar asked Mar 23 '23 10:03

L_Holcombe


1 Answers

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');
like image 105
Matt Avatar answered Apr 04 '23 22:04

Matt