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 filtera
inside#foo
.
And it does not look efficient.
Is that correct? And if yes, how should we do that in a better way?
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).
Description. "$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.
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.
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