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?
You can't. A pseudo element is not in the DOM so can't be selected by JS.
Since they're not part of the DOM, CSS pseudo-elements can't be selected and edited with JavaScript the same way as traditional elements on a page.
The following selector: $("div") selects only the first div element in the HTML document. The following jQuery statement will select all of the elements on the HTML document. With jQuery, look at the following selector: $("div.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With