Reputation: 3880
we can use $('body>div:lt(2)')
to get the first 2 DIV
s 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 DIV
s 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
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 div
s in s
, and your filtered div
s 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