13

This is a pretty academic question. I'm wondering how the browser is implemented as in what data structure or algorithm is used to map a CSS selector to a particular DOM element. Is it accomplished through a hash table? How does DOM child node knows that the style applied to parent also applies to itself etc. I've been looking at Mozilla developer center and haven't found anything. Any documentations or books on the subject would be much appreciated... thanks!

Jlam
  • 1,812
  • 1
  • 19
  • 26

4 Answers4

10

Matching answers question "which selectors match given node", not "which nodes match a selector". This lets you simply evaluate each part of a selector against current node (compare node name/ID/class). Decendant combinator and inheritance are done through scanning of parent nodes.

If you're interested what happens next, WebKit blog had nice series: WebCore rendering basics

Kornel
  • 91,239
  • 30
  • 200
  • 278
2

So here are the scarce docs:

From your question it seems that you should first learn more about how CSS is supposed to work (e.g. what is rule specificity, computed style).

Nickolay
  • 28,261
  • 8
  • 94
  • 160
  • 1
    I am very aware of how CSS works with regards to rule specificty, computed style. I was interested in the actual implementation details of the rendering engine(s). Your answer does not shed any light in that aspect. – Jlam Feb 25 '13 at 08:23
  • @Jlam: Thanks for coming back 3.5 years later to tell me that! I'm sorry if I offended you, but your question didn't make that clear and you really have to know CSS before delving into the implementation. FWIW, I learned the basics how mozilla's style system worked by reading through those pages and then through the implementation linked in Ewan's answer. – Nickolay Feb 25 '13 at 20:38
1

You mention Mozilla. It is certainly easier answer your question in the context of a particular concrete implementation, rather than the abstract notion of all possible implementations.

[W]hat data structure or algorithm is used to map a CSS selector to a particular DOM element ... is it accomplished through a hash table?

I suppose the direct answer to your question, for FF2, is likely to be in the style directory of the firefox source code. A search within that directory for "hashtable" yields 111 results in 7 files.

I feel confident that hashtables are broadly associated with some of the processes involved in rendering CSS styles.

So the short answer to your question is, "Yes, but there's more to it than just hash tables."

Ewan Todd
  • 7,153
  • 23
  • 33
1

W3C provides a general approach from a definition standpoint which I find informative:

Tyler Wright
  • 171
  • 2
  • 4