What is the most efficient way to find the next element in a jQuery selector list?

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 single item descriptor inside this list:

 // the 11th such link: var current = list.slice(10, 11); 

What is the most efficient way to find before and after links in a list ? Keep in mind that the selector is active and that entries can be added or removed between getting current and trying to find the next or previous link.

The best I can come up with is to bypass the O (n) 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; } 
+4
source share
3 answers

I was just looking for an example of Steve Wellens. Mine is a little nastier, but supports the same interface and offers the flexibility to work with a changing DOM.

http://jsfiddle.net/sJwJL/

The main function:

 var itr = function(selector){ var last_element = null; return { next : function(){ var elements = $(selector); var last_index = 0; if(last_element != null){ elements.each(function(item){ if(item == last_element){ last_index = index+1; return; } }); } last_element = $(elements[last_index]); return last_element; } }; }; 
+1
source

I'm sure this is also O (n) complexity, but would the syntax not be much simpler with .index() ?

 function next() { var currList = $(list.selector), idx = currList.index(current); return idx >= 0 && idx < currList.length-1 ? currList.slice(idx+1,idx+2) : undefined; } function prev() { var currList = $(list.selector), idx = currList.index(current); return idx > 0 ? currList.slice(idx - 1, idx) : undefined; } 

For a complete example, see http://jsfiddle.net/yAFr5/12/ .

0
source

This is a little klunky, but it works:

http://jsfiddle.net/zHDws/

-1
source

Source: https://habr.com/ru/post/1346640/


All Articles