DOM Construction

How the browser builds the Document Object Model tree from parsed HTML nodes.

Internet5 min readConcept 25 of 35

What it is

The DOM (Document Object Model) is the browser's internal representation of the HTML document. It is a massive tree-like data structure.

As the parser emits Nodes (from the Parsing Phase), it links them together into the DOM tree, capturing parent-child relationships, text content, and attributes.

Why it matters

The DOM is the *only* way JavaScript can interact with the page. JS does not read your HTML string; it queries and mutates the DOM tree.

Because the DOM is a massive tree, manipulating it with JavaScript can be computationally expensive, which is why libraries like React invented the Virtual DOM.

How it works

The browser starts with a root Document node.

As the parser reads <html>, it attaches an HTMLHtmlElement node to the Document.

When it encounters nested tags like <body> and <p>, it creates HTMLBodyElement and HTMLParagraphElement nodes, attaching them as children of their parent nodes.

When a closing tag </p> is encountered, the parser moves back up the tree, ready to attach the next sibling.

Try it

Watch how a nested HTML structure maps perfectly into a parent-child DOM tree.

<!-- Invalid HTML -->
<html>
<body>
<!-- Missing closing paragraph tag -->
<p>Hello
<!-- Div inside paragraph! -->
<div>World</div>
HTMLHtmlElement
HTMLBodyElement
HTMLParagraphElement
#text: "Hello"
HTMLDivElement!
#text: "World"

Notice how the browser auto-corrects the invalid HTML (a div inside a missing-closure p tag) into a valid, flat DOM tree.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if your HTML contains an unclosed `<p>` tag followed by a `<div>`?
  2. 2In the DOM tree, what is the relationship between `<body>` and `<h1>` if the h1 is directly inside the body?
  3. 3How does JavaScript view the DOM?

Remember this

  • The DOM is a tree of Node objects, not an HTML string.
  • The DOM is living and mutable by JavaScript.
  • Browsers auto-correct invalid HTML when building the DOM tree.

Done with this concept?

Mark it complete to track your progress. No login needed.