views:

186

answers:

3

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");
+2  A: 

It looks like one possible answer is:

divs.filter(":eq(0)").addClass("selected");
spig
Using `eq()` method instead of `filter()` with the `:eq` selector is slightly more efficient since jQuery doesn't have to parse the string.
brianpeiris
+1  A: 

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.

pst
+4  A: 

Just use the eq() method:

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