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

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

 var s = $('body>div') 

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

+5
source share
1 answer

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

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

Note that this does not change the original value of s , so you will have your entire div in s and your filtered div in filtered .


Alternatively, as you said and discussed in the comments, you can use Array.prototype.slice .

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

This is technically faster than .filter() . However, this may also make your code less readable / understandable. The increase in productivity can also be extremely small if you do not perform this operation many thousands of times or more in a very short period of time.

Readability and performance is a battle often battled in programming, and ultimately you are the only one who can decide which one will win for your own code.

+5
source

Source: https://habr.com/ru/post/1214191/


All Articles