Be specific on the right-hand side of your selector, and less specific on the left.
// unoptimized
$('div.data .gonzalez');
// optimized
$('.data td.gonzalez');
Quote Source
Could someone explain why the less specific left is faster as a CSS selector?
Is this a Sizzle thing or does the same apply for document.querySelectorAll
?
Are there any speed gains using "similarly optimised" CSS selectors in CSS files?
jQuery's Sizzle Engine parse selectors from right to left, so it's true. There are exceptions though, for example when the first operand is an ID. Then the search will operate in the context of the element with this ID. That's a particularity of the Sizzle Engine, but I don't know how querySelectorForAll is implemented.
An example:
$('div.data .gonzalez');
Sizzle will get all the DOM elements with class gonzalez then check for each if an ancestor is a div tag with class data
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