CSS Selectors performance, DOM Parsing
dom, javascript, jquery, jquery-selectors
Solution
Well, an `#id` selector is faster than class selectors because: (a) there can only be one element with a given id value; (b) browsers can hold a map `id -> element`, so the `#id` selector can work as quick as a single map lookup.
Next, the first option suggested above is definitely faster, as it avoids the second lookup, thereby reducing the total selector-based lookup time by a factor of 2.
Last, you can use Chrome Developer Tools' Selector Profiler (in the Profiles panel) to profile the time it takes a browser to process selectors in your page (match + apply styles to the matching elements.)
Problem
My question is related to DOM parsing getting triggered, i would like to know why it's faster to use a CSS ID selector than a Class selector. When does the DOM tree have to be parsed again, and what tricks and performance enhancements should I use... also, someone told me that if I do something like ``` var $p = $("p"); $p.css("color", "blue"); $p.text("Text changed!"); ``` instead of ``` $("p").css("color", "blue"); $("p").text("Text changed!"); ``` improves performance, is this true for all browsers? Also how do I know if my DOM tree has been re-parsed?