Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the jQuery selector $('#foo a') evaluated?

As a example of jQuery code (https://coderwall.com/p/7uchvg), I read that the expression $('#foo a'); behaves like this:

Find every a in the page and then filter a inside #foo.

And it does not look efficient.

Is that correct? And if yes, how should we do that in a better way?

like image 895
Afshin Mehrabani Avatar asked Dec 03 '12 07:12

Afshin Mehrabani


People also ask

What does the jQuery selector return?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).

What would $(' div p ') Select in jQuery?

Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.


1 Answers

That is correct - Sizzle (jQuery's selector engine) behaves the same way as CSS selectors. CSS and Sizzle selectors are evaluated right-to-left, and so #foo a will find all a nodes, then filter those by nodes that descend from #foo.

You improve this by ensuring that your leaf selectors have a high specificity, usually by giving them a class or ID.

like image 86
Chris Heald Avatar answered Sep 28 '22 01:09

Chris Heald