4

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');
L_Holcombe
  • 387
  • 2
  • 8
  • [link]http://stackoverflow.com/questions/10004593/how-jquery-data-breaks-circular-reference – Plamen Jun 25 '13 at 23:24

3 Answers3

5

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');
Matt
  • 74,352
  • 26
  • 153
  • 180
  • Just what I was in the process of typing :) – Mike Brant Jun 25 '13 at 23:27
  • In case anybody is curious, this function can be rewritten to traverse the opposite direction simply by changing next -> prev, and first -> last. I called it prevOrLast. Thanks again for the help. – L_Holcombe Jun 26 '13 at 05:30
2

I sometimes use

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

yeah, crazy :D

David Fregoli
  • 3,377
  • 1
  • 19
  • 40
0

Not exactly sure what you're asking or trying to achieve here but if you merely want to add a class to the first element you can do this

Traverse the dom to find the parent element

Find the first child of that element - like this

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

splig
  • 371
  • 1
  • 4
  • 11