shenkwen
shenkwen

Reputation: 3880

How can we apply pseudo selector to a jQuery DOM variable?

we can use $('body>div:lt(2)') to get the first 2 DIVs in the body, if body>div has been assigned to a variable:

var s = $('body>div')

can we still use the pseudo selector or other ways to get the first 2 DIVs in refrence to the variable? Of course, s:lt(2) won't work. What I can think of is $(s.slice(0,2)), but is there any better way to do this?

Upvotes: 5

Views: 97

Answers (1)

ajp15243
ajp15243

Reputation: 7950

You can use jQuery's .filter() method, which allows, among other things, a selector argument for filtering the selected nodes in a jQuery object.

var filtered = s.filter(':lt(2)');

Note that this does not modify the original value of s, so you'll have all of your divs in s, and your filtered divs in filtered.


Alternatively, as you've already stated and has been discussed in the comments, you can use Array.prototype.slice.

var sliced = $(s.slice(0,2));

This technically performs faster than .filter(). However, it also may make your code less readable/understandable. The performance gain is also likely to be extremely negligible unless you perform this operation many thousands of times or more in a very short period of time.

Readability vs. performance is a battle fought often in programming, and ultimately you're the only one who can decide which one wins out for your own code.

Upvotes: 5

Related Questions