As a example of jQuery code (https://coderwall.com/p/7uchvg), I read that the expression $('#foo a'); behaves like this:
Find every
ain the page and then filterainside#foo.
And it does not look efficient.
Is that correct? And if yes, how should we do that in a better way?
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 awill find allanodes, 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.