How do I further filter a jquery element array while not running the jquery search again?
Given the following code, how do I use the variable divs creat开发者_StackOverflowed 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");
Just use the eq()
method:
divs.eq(0).addClass('selected');
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')
精彩评论