jQuery's next()
function returns the next sibling as they appear in the DOM tree (not in jQuery resultset) for all matched elements. So calling
$("#container .swaps:first")
gets the first anchor, and calling next()
on it returns undefined as it has no next sibling. I think you might want to implement the Iterator pattern if you want to access the nodes successively by calling next()
.
The jQuery object is an array of items. You could just store the current index in a variable, and increment it after getting the next element.
// Naive way
var items = $("#container .swaps");
var i = 0;
items[i++] // first <a>
items[i++] // second <a>
Here are two implementations that wrap the above functionality using the Iterator pattern - one that works as a jQuery plugin, the other is basically a separate function. Both work the same:
// Iterator function
function Iterator(list) {
var results = list;
var i = 0;
this.next = function() {
return results[i++];
};
return this;
}
// Usage
var iterator = Iterator($("#container .swaps"));
iterator.next() // first <a>
iterator.next() // second <a>
The second one is almost identical to the first one, but is used a jQuery plugin instead:
// jQuery plugin
$.fn.iterator = function() {
var i = 0;
this.next = function() {
return this[i++];
};
return this;
};
// Usage
var iterator = $("#container .swaps").iterator();
iterator.next() // first <a>
iterator.next() // second <a>
Javascript 1.7 has some cool features in generators and iterators for doing just this, but it's not still not widespread - only Firefox supports it as far as I know.