1

When using JavaScript we query the DOM via getElementById (or getElementsByTagName, etc.), at a lower level is the browser performing a search using depth-first search (pre-order)?

ContentiousMaximus
  • 1,284
  • 3
  • 14
  • 24
  • 1
    Logically it makes sense that the answer would be yes. However, implementation varies from browser to browser, and ultimately it really doesn't matter as long as the result matches the spec. – Anthony Grist Jan 22 '14 at 16:34
  • 1
    The DOM spec doesn't mandate specific algorithms: it's just an API. And I don't think it makes sense to use the same algorithm to find by IDs (which are unique) than by class (which can repeat). – Álvaro González Jan 22 '14 at 16:35

2 Answers2

1

It's irrelevant, isn't it? The actual implementation is not specified, only the result is interesting.

getElementById is usually optimized by a lookup table, so there's no tree search at all.

document.getElementsByTagName is returning a HTMLCollection (see also document order for DOM selection method) that is sorted in "tree order":

In tree order is preorder, depth-first traversal of a tree.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

It is an interesting question. It depends on implementation, I guess that Hash is another possible data structure to do it.

There are a similar question here: What is the implementation of GetElementByID()?

Community
  • 1
  • 1
Danilo
  • 93
  • 11