documenthtmlbodyli"Milk"ultodo.html• Milk• Eggs1<style>.new { font-weight: bold; }</style>2<ul id="list"><li>Milk</li></ul>3<script src="todo.js"></script>listitem1const list = document.querySelector("#list");2const item = document.createElement("li");3item.textContent = "Eggs";4list.append(item);5item.classList.add("new");6list.firstElementChild.remove();7console.log(list.children.length);Console1todo.js:7liEggs.new1
Back: the DOM tree (node objects joined by branches) and the browser windowFront: todo.html and todo.js, the variables list and item, and the consoleTokens: a search, a reference, the text, the class, a count and a redrawAt the back, the DOM tree the browser built from todo.html, and the browser window showing the page. In front, the two files as cards, the two variables and the developer console. Each line of todo.js changes the tree at once: find the ul, make an li, give it text, append it, add a class, remove Milk, count the children. The screen only catches up when the script has finished. The figure shows only element nodes. The real tree also has a head element (the style element is placed in it), the script element, and text nodes: the text Milk is itself a text node inside the li, and the line breaks between the tags become text nodes too.

The page as a tree

  1. The browser reads todo.html and builds the DOM: a tree of objects called nodes. document is the root. Below it sit html, body and the ul, whose child is an li holding the text Milk.

Finding and making nodes

Changing the tree

Reading it back

What happens

// step 1/9 · tree
todo.html   <ul id="list"><li>Milk</li></ul>
browser     builds one object (node) per element
tree     document → html → body → ul → li "Milk"
parent      ul is the parent of li; li is its child
JavaScript  reads and changes this tree

The figure shows only element nodes. The real tree also has a head element (the style element is placed in it), the script element, and text nodes: the text Milk is itself a text node inside the li, and the line breaks between the tags become text nodes too. list and item hold references to node objects, not copies. Changing an element through a variable changes the one node in the tree.