Skip to content
jshacks.dev
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.

The Document Object Model is the browser's live, in-memory representation of a page, and nearly everything JavaScript does in a browser is a read or a write against it. A common source of confusion is that the DOM contains more than the tags you see in the HTML: text, comments and the document itself are all nodes, and the properties you use to walk the tree come in two families, one that sees every node and one that sees only elements. This post explains the node types, the two families of navigation properties, how whitespace creates text nodes, and how to inspect a tree. The definitive source is the DOM Standard, and the MDN DOM introduction covers the same ground in a more tutorial form.

From HTML to a tree

The browser parses HTML into a tree of objects. Each tag becomes an element node, text between tags becomes a text node, and the whole structure hangs from a document node. Consider this page.

page.htmlHTML
<!doctype html>
<html>
  <body>
    <ul id="list">
      <li>One</li>
      <li>Two</li>
    </ul>
    <!-- end of list -->
  </body>
</html>

The tree has a Document at the root, with a DocumentType node for the doctype and an html element as its children. The html element has head and body children. Notice that the source has no <head>, and the parser inserted one anyway. The DOM is the result of parsing, with the same repairs a browser makes for sloppy markup, not a copy of the source text.

Each node is an object with a nodeType number and a nodeName. The types you meet constantly are these.

NodenodeTypenodeNameExample
Element1tag name in upper case<li> gives LI
Text3#textthe characters One
Comment8#comment<!-- end of list -->
Document9#documentdocument
DocumentType10doctype namehtml
DocumentFragment11#document-fragmenta detached container

Elements are nodes, but nodes are not all elements

This is the central distinction. Node is the base interface: it has nodeType, parentNode, childNodes and so on. Element extends Node and adds what only tags have: tagName, id, classList, attributes and querySelector. A text node has no classList, and trying to call querySelector on it fails.

types.jsJavaScript
const list = document.getElementById("list");

console.log(list.nodeType, list.nodeName);
console.log(list instanceof Element, list instanceof Node);
console.log(list.firstChild.nodeType, list.firstChild.nodeName);
console.log(list.firstChild instanceof Element);
Text
1 UL
true true
3 #text
false

The first child of the ul is not the first li. It is the whitespace between <ul id="list"> and <li>: a newline and spaces, which the parser keeps as a text node. That is the single most common surprise in DOM code.

Two families of navigation

Every node has properties for moving through the tree. There are two sets, and picking the wrong one is the source of a lot of bugs.

Sees all nodesSees elements only
childNodeschildren
firstChildfirstElementChild
lastChildlastElementChild
nextSiblingnextElementSibling
previousSiblingpreviousElementSibling
parentNodeparentElement

The left column includes text and comment nodes. The right column skips them.

navigate.jsJavaScript
const list = document.getElementById("list");

console.log(list.childNodes.length);
console.log(list.children.length);

console.log(list.firstElementChild.textContent);
console.log(list.lastElementChild.textContent);
console.log(list.firstElementChild.nextElementSibling.textContent);
Text
5
2
One
Two
Two

childNodes has five entries: a whitespace text node, the first li, a whitespace text node, the second li, and a trailing whitespace text node. children has just the two li elements. Use the element-only properties unless you have a reason to see text, which keeps whitespace from leaking into your logic.

parentNode and parentElement differ in one case: for the root html element, parentNode is the document, while parentElement is null, because the document is not an element.

Reading and changing text

A text node holds characters, in its data or nodeValue. The element-level property textContent gives you the concatenated text of a whole subtree, and is the usual way to read or replace text.

text.jsJavaScript
const list = document.getElementById("list");

console.log(JSON.stringify(list.textContent));

const first = list.firstElementChild;
first.textContent = "Uno";
console.log(first.outerHTML);
Text
"\n      One\n      Two\n    "
"<li>Uno</li>"

Reading textContent of the ul includes the whitespace between items, as the escaped string shows. Setting textContent removes all child nodes and replaces them with a single text node, and it treats the string as plain text, not HTML, so it is safe for untrusted input. The related innerHTML and innerText properties behave differently and have their own post.

Comments and other nodes

Comments are nodes too, and they appear in childNodes.

comments.jsJavaScript
const body = document.body;

for (const node of body.childNodes) {
  if (node.nodeType === Node.COMMENT_NODE) {
    console.log("comment:", node.data.trim());
  }
}
Text
comment: end of list

Node.COMMENT_NODE is the named constant for 8, and using the names makes the code readable. Walking a whole subtree, including text, is easier with a TreeWalker, which can filter by node type.

walker.jsJavaScript
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);

let count = 0;
while (walker.nextNode()) {
  if (walker.currentNode.data.trim() !== "") {
    count += 1;
  }
}

console.log("non-empty text nodes:", count);
Text
non-empty text nodes: 2

Creating and attaching nodes

You build nodes with the document factory methods and attach them with methods on a parent.

create.jsJavaScript
const list = document.getElementById("list");

const item = document.createElement("li");
item.textContent = "Three";
list.append(item);

const note = document.createComment("added by script");
list.append(note);

console.log(list.children.length);
console.log(list.lastChild.nodeType);
Text
3
8

append accepts nodes and strings, and adds them at the end. A node can have only one parent, so appending a node that is already in the tree moves it. To add many nodes at once, build them in a DocumentFragment, which is a lightweight container that disappears when you insert it, leaving its children behind, so the page updates and re-renders once.

Live and static collections

The collections returned by the navigation properties update as the tree changes, and the ones returned by querySelectorAll do not. childNodes is live, and children is live too. That matters when you loop and change the tree at the same time, a topic covered in the post on NodeList and HTMLCollection.

Inspecting a tree

The browser's developer tools show the DOM, not the source. The Elements panel renders the live tree, so changes your scripts have made are visible there, and the text nodes between elements are collapsed in the display. In code, console.dir(node) prints the object's properties instead of its markup, and node.outerHTML gives the serialization of an element and its subtree. If you suspect whitespace text nodes in a loop, log node.nodeType and the problem becomes plain.

Why the tree matters in practice

Knowing the tree shape saves time on three everyday tasks. When a selector returns nothing, the cause is often that the element does not exist yet, because the script ran before the parser reached it, and the DOM at that moment is a partial tree. When a loop over childNodes produces strange results, whitespace text nodes are usually in it. And when a framework re-renders, it changes the tree in place, so any node reference you saved may now be detached from the document, which you can check with node.isConnected.

The tree also explains performance. Every change to it can invalidate styles and layout, and a deep tree with thousands of nodes costs more to update than a shallow one. Reading from the tree is cheap, and the expensive part is the work the browser does after a write. Build detached structures in memory, attach them once, and keep the node count of the page modest.

Shadow trees and fragments

Two related ideas complete the picture. A shadow root is a separate tree attached to an element, used by web components to hide their internals. Its nodes are not part of the main document's tree, so querySelector from the document does not reach inside, and children of the host does not list them. A document fragment is a detached tree with no parent, and the nodes you append from it move into the document while the fragment becomes empty. Both use the same node interfaces described here, so the properties and methods work the same way once you hold a reference.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.