I have a jQuery selector of arbitrary complexity:
// a bunch of links:
var list = $('#foo').find('li.bar a, li.baz a');
I have a handle on one element within that list:
// the 11th such link:
var current = list.slice(10, 11);
What’s the most efficient way to find the links before and after in list? Keep in mind that the selector is live and that entries may be added or removed between getting current and trying to find the next or previous link.
The best I can come up with is a O(n) traversal of list:
function adjacentInList(list, target, direction) {
var delta = (direction === 'prev' ? -1 : 1);
list = $(list);
target = $(target);
var result = null;
list.each(function(index, element) {
if (target[0] === element) {
result = list.slice(index + delta, index + delta + 1);
}
});
return result;
}
I just forked Steve Wellens example. Mine is a bit nastier but maintains the same interface and offers the flexibility of working with a changing DOM.
http://jsfiddle.net/sJwJL/
Primary function: