views:

51

answers:

2

I have an arbitrarily deep list of the form:

<ul>
 <li></li>
 <li>
  <ul>
   <li></li>
  </ul>
 </li>
</ul>

I am trying to build a function "nextElement" that returns a jQuery selector.

The first time the function is called, it returns the first li in the list. The second time it is called, it returns the next li in the page. Etc.

I'd like this function to pay no attention to siblings, parents, children, etc. All I care about is that everytime it is called, the next li in the source gets chosen.

Any suggestions on how to go about approaching this?

Thanks

A: 

Probably best to modify the concept of nextElement to be more like this:

(function($) {
    var index = -1;
    jQuery.fn.nextElement = function() {
        index = (index + 1) % this.length;
        return this.eq(index);
    }
})(jQuery);

You can use it like this:

$("li").nextElement(); // returns first li
$("li").nextElement(); // returns second li

etc...

lark
The only problem with this solution is that it won't reset per logical selector. Could be extended easily to account for multiple logical selectors. As your question stands this should be a reasonable solution.
lark
+2  A: 

The no-jQuery solution..

function getIterator(){
    var nodes = document.getElementByTagName("li");
    var index = 0;
    return {
        next: function(){
            return nodes[index++];
        },
        hasNext: function(){
            return index < nodes.lenght - 1;
        }
    };
}

Then use

var iterator = getIterator();
while (iterator.hasNext()){
    var node = iterator.next();
    console.log(node.innerHTML);
    // if you want to just wrap the node in $(node)....
}

or the more efficient

var iterator = getIterator(), node;
while ((node = iterator.next())){
    console.log(node.innerHTML);
    // if you want to just wrap the node in $(node)....
}
Sean Kinsey
nice! works great. thanks.
Travis