Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selection. Find element after another

<li>
  <select id="foo"></select>
</li>
<li>
  <select id="bar"></select>
</li>
<li>
  <select id="baz"></select>
</li>

var select_after = function(src){
   //How get all select elements after the one specified as argument ?
}

How write this method ?

select_after($("#foo")) 

should return #bar and #baz elements in array

select_after($("#bar"))

should return #baz element in array

select_after($("#baz")) 

should return empty array

How should I write this method ?

like image 922
astropanic Avatar asked Jan 19 '23 18:01

astropanic


1 Answers

For a simple single-liner you could use the following chain:

$("#foo").parent().nextAll().children("select");

The code above will first select the parent, which is the li element, then select all of the siblings that comes after it, and finally return the select elements within. As seen in this fiddle.

However, this method is both bulky and slow since you are walking the DOM. Another method that I rather use because it is way faster when working with a larger set of elements,

Preselection of all select elements, then create an object with references of the id to the index by looping them. Now you can just splice the jQuery object to get the elements that comes after (or before).

// Preselect select elements
var selects = $("ul > li > select"),
    // Prepare empty object to hold index reference
    idx = {};

// Loop through the select elements and build index reference
selects.each(function(i){idx[this.id] = i;});

// Get select elements after #foo
console.log(selects.slice(idx.foo+1));

// Get select elements before #baz
console.log(selects.slice(0, idx.baz));

Check out the above method in this fiddle.

like image 168
mekwall Avatar answered Jan 27 '23 22:01

mekwall