The DOM

The browser reads a page's HTML text once and turns it into a tree of objects in memory, the Document Object Model. It draws the page from those objects, and JavaScript changes the page by changing them. The HTML text itself is then set aside. Notes. For more of JavaScript's DOM functions, see DOM API.

1. HTML in, DOM out

Type or edit HTML on the left. The browser's parser turns it into the tree on the right, the same way it does for a whole page. The tree has no closing tags, because objects don't need them: indentation shows what's inside what.

Try:

HTML (text you write)

DOM (objects the parser built)


  

Drawn from the DOM

Back to HTML

The tree written out again as text (outerHTML). Every closing tag here was generated, not remembered. Compare it with what you typed.


  

2. Building the DOM from JavaScript

Section 1 built a tree from HTML text. Here JavaScript builds one with no HTML at all, by calling DOM functions. The only thing written in this page's HTML is an empty <div id="stage"> to build in. Each button runs the JavaScript it adds to Code run so far, exactly as written there.

3. Add more:

The page

The tree behind it


  

Code run so far

Each block runs on its own, as a separate function. That's why every block finds the list again with getElementById, and why each can have its own const li.