Hacker News new | ask | show | jobs
by lince 4862 days ago
Do really selectors work that way?

I always though that if I had:

#social a

The browser first get the social, then the "a" tag and analyze and store it in some DOM tree style information.

3 comments

I thought the same. If this is true (it finds <a> elements then looks for the id), I've been writing a lot of poor-performing selectors.

Edit: I found that it does work this way, and the reason is because browsers process content and apply CSS top to bottom as it renders, they do not first load all the content and then apply CSS rules.

From http://snook.ca/archives/html_and_css/css-parent-selectors

If you have a rule like body div#content p { color: #003366; } then for every element—as it gets rendered to the page—it'll first ask if it's a paragraph element. If it is, it'll work its way up the DOM and ask if it's a div with an ID of content. If it finds what it's looking for, it'll continue its way up the DOM until it reaches the body.

Yes, selectors really match from right to left

Boris Zbarsky gives a good explanation of why here: http://stackoverflow.com/questions/5797014/why-do-browsers-m...

That bit certainly surprised me. It seems like a simple optimization to scan a selector for the most efficient parts and use that as your starting point (with ids being a no-brainer).

Obviously given the selector "div #foo a {}" (obviously a dumb selector, but...) it would be smarter to look for #foo and verify it was inside a div than get every div and search for a #foo. And by extension "div .foo a {}" (assuming .foo really is way more efficient than div, which again I find hard to believe given there's native support for getElementsByTagType).

It seems to me that the effectiveness of using classes probably stems from browsers optimizing against use cases like "OMG folks are using Dijit and hanging twelve classes off every div". There's no reason I can see why class selectors ought to be especially efficient, especially if -- say -- your markup has lots of classes and relatively few attributes (and isn't that more common these days?).

We should also probably differentiate between CSS selectors as affects page rendering and CSS selectors as affects grabbing a bag of nodes using jQuery $() or document.querySelectorAll().