Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 922
shenkwen Avatar asked Feb 25 '15 19:02

shenkwen


People also ask

How do I target a pseudo element in jQuery?

You can't. A pseudo element is not in the DOM so can't be selected by JS.

Can you select pseudo element in JavaScript?

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.

What does the code $( Div select?

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.


1 Answers

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.

like image 89
ajp15243 Avatar answered Sep 21 '22 14:09

ajp15243