Track 01 · Lesson 8 of 9How the web works

Track 01 · How the web works

From HTML to a tree

Lesson 8 of 9· 8 min

The browser reads your HTML and builds a tree of nodes: elements, text and comments, each one a JavaScript object. Edit the HTML and watch the tree rebuild.

Watch HTML become a tree

Edit the HTML, or click the preview

What the browser draws (click something)

The DOM tree

0 elements, 0 text nodes

Every tag becomes an element node, and the text between tags becomes text nodes. Click a node in the tree, or click something in the preview.

Nodes, not text#

Once the browser has parsed your page, your HTML file is no longer what matters. What matters is the DOM, the Document Object Model: a tree where every element and every piece of text is an object you can find, read and change from JavaScript.

  • Every tag becomes an element node.
  • The text between tags becomes text nodes, including the whitespace you used for indenting.
  • Elements nest, so every node has a parent, and most have children.

The browser fixes your mistakes#

Try the Broken HTML preset. Unclosed and wrongly nested tags don't crash anything: the HTML standard spells out exactly how to repair them, so every browser builds the same tree. The table preset shows the parser adding a tbody you never wrote, which is why table.firstElementChild isn't your row.

That's the key idea: the DOM is the browser's version of your page, not yours.

Check yourself

Your HTML puts a tr directly inside a table. What does table.firstElementChild return?