Writing performant CSS selectors
Even though Sizzle (jQuery's selector engine) hides the complexity of DOM traversals based on complex CSS selectors, we should have an idea of how our selectors are performing. Understanding how CSS selectors are matched against the elements of the DOM helps us write more efficient selectors which perform better when used with jQuery.
The key characteristic of efficient CSS selectors is specificity. According to this, ID and Class selectors are always more efficient than selectors with many results like div
and *
. When writing complex CSS selectors, keep in mind that they are evaluated from the right to the left and that a selector gets rejected after recursively testing it against every parent element until the root of the DOM.
As a result, try to be as specific as possible with the rightmost selector in order to cut down the matched elements as quickly as possible during the execution of the selector.
// initially matches all the anchors of the page...