How do I further filter a jquery element array while not running the jquery search again?

StackOverflow https://stackoverflow.com/questions/1616293

  •  06-07-2019
  •  | 
  •  

Question

Given the following code, how do I use the variable divs created by the first jQuery selector, without rerunning it on the line where I add the class?

So, given this:

var divs = $("div.searchhit");

// more code here using divs.length divs.removeClass("selected"); $("div.searchhit:eq(0)").addClass("selected");

How do I get the last line to look like this:

divs(":eq(0)").addClass("selected");
Was it helpful?

Solution

Just use the eq() method:

divs.eq(0).addClass('selected');

OTHER TIPS

It looks like one possible answer is:

divs.filter(":eq(0)").addClass("selected");

Please read the jQuery documentation. This is well covered.

That was a bit terse of me. Here small explanation:

jQuery(query) is the primary filter which searches from the root of the DOM. Subsequent queries run on the resultant object start on that set. If no expanding operations are performed (say, looking at children within a previously matched node) then the resulting query can contain at most as many elements as the previous query.

If you want to for example select child elements (instead of filtering by them), use:

$('tr').children('td')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top