When rendering web pages and applying styles, do browsers index ID’s and class names for efficient search, or does it traverse the entire DOM from the top each time an ID or class name is specified to reach the correct element.
I’m wondering for optimisation reasons, and whether it’s worth giving the browser hints (longer selectors) to where an object of a certain ID is. I.e.
#container #one-of-many-container-siblings #my-id
instead of:
#my-id
Will the former yield better performance if the DOM is quite large?
It actually works the opposite way to what you’re thinking.
Remember that browsers parse CSS selectors right to left.
This:
will take more steps to match than this:
See: http://www.css-101.org/descendant-selector/go_fetch_yourself.php
Considering the question you’ve just asked, I recommend you read this article:
http://css-tricks.com/efficiently-rendering-css/
It will help you write more efficient selectors: