Writing
The Document Object Model in JavaScript: Trees, Nodes, Attributes and Events
The DOM is the browser’s API to the page: a tree of nodes that JavaScript reads and changes. Here’s how the tree, node types, attributes and events work, and the modern APIs to use.
By Ka Lun Chan · Web development / Learning
What is the Document Object Model in JavaScript?
The Document Object Model (DOM) is an API to HTML and XML documents. The browser turns the page into a tree of objects, and JavaScript uses the DOM to read and change the page’s content, structure and style.
I first wrote this on my old blog for people learning JavaScript. This version keeps the explanation that held up, fixes a few mistakes in the original, and adds the APIs I’d reach for today.
Any time a website runs a slideshow, opens a menu or shows an error message under a form field, that’s JavaScript accessing and changing the DOM. MDN makes a point worth knowing early: the DOM is a web API the browser provides, separate from the JavaScript language. Node.js runs JavaScript without it, which is why document is undefined in a Node script.
| Task | Modern API | Watch out for |
|---|---|---|
| Find one element | querySelector(".card") | Returns null when nothing matches, so check before using it. |
| Find many elements | querySelectorAll("li") | Returns a static NodeList. It has forEach but isn’t an array. |
| Change text | el.textContent = text | Replaces every child node of the element. |
| Insert markup | el.innerHTML = html | Never pass untrusted strings. That’s how XSS gets in. |
| Change styling | el.classList.toggle("active") | Prefer classes in CSS over long runs of inline style. |
| Read or set attributes | getAttribute / setAttribute | An attribute and a property (input value) can differ. |
| React to the user | addEventListener("click", fn) | One listener on a parent beats hundreds on children. |
| Add many nodes | parent.append(...nodes) | Build first, insert once. Optimize for readability. |
| Inside React | useRef and ref={...} | Don’t remove or rewrite nodes React renders. |
Why is the DOM described as a tree?
Because HTML elements nest. Each element has one parent and can have children, so the browser represents the page as a tree with the document at the root, and you move around it through parents, children and siblings.
Here’s the small page from the original post:
<!DOCTYPE html>
<html>
<head>
<title>text</title>
</head>
<body>
<nav>Home</nav>
<p>Content <b>bold text</b></p>
</body>
</html>And here’s the tree the browser builds from it. The original listing showed a <div> where the HTML had a <p>, which is fixed here. I’ve also left out the whitespace text nodes the browser creates between tags, which browser developer tools usually hide too.
document
├── <!DOCTYPE html> (doctype node, not an element)
└── <html>
├── <head>
│ └── <title>
│ └── "text"
└── <body>
├── <nav>
│ └── "Home"
└── <p>
├── "Content "
└── <b>
└── "bold text"Are all nodes elements?
No. All elements are nodes, but not all nodes are elements. Text, comments, the document itself and the doctype are nodes too. The doctype sits outside the <html> tag and isn’t an element at all.
The original post said there are 12 node types. That needs some nuance. The Node interface does define twelve nodeType constants, but the DOM Living Standard marks three of them as legacy and MDN lists them as deprecated and no longer in use: entity reference (5), entity (6) and notation (12). CDATA sections (4) only appear in XML documents.
In an HTML page the ones you’ll actually meet are element (1), text (3), comment (8), document (9), doctype (10) and document fragment (11):
document.firstChild.nodeType; // 10, DOCUMENT_TYPE_NODE
document.firstChild.nodeName; // "html"
document.documentElement.nodeType; // 1, ELEMENT_NODE (<html>)
document.querySelector("b").firstChild.nodeType; // 3, TEXT_NODE
// The doctype is a node but not an element
document.childNodes.length; // 2: the doctype and <html>
document.children.length; // 1: only <html>That last pair is the practical difference. childNodes returns every node, while children returns only elements, which is usually what you want.
Are attributes nodes in the DOM tree?
Not in the modern DOM. Attributes are still represented as Attr objects, which inherit from Node, but they never have a parent or children. You reach them through the element that owns them.
The original post listed attributes alongside text and elements as common node types in the tree. The standard is clear that attributes stay out of the tree: an Attr belongs to its element through ownerElement and doesn’t show up in childNodes. In daily work you rarely touch Attr objects anyway. You read and write attributes with methods on the element:
document.body.hasAttributes(); // true if <body> has any attribute
document.body.hasAttribute("style"); // true only if a style attribute is set
document.body.getAttribute("class"); // the value, or null
// Attributes are not children
document.body.childNodes; // elements, text and comments only
document.body.attributes; // a NamedNodeMap of Attr objectsOne correction to the original example: document.body.hasAttribute("style") returns true only if the body has a style attribute. On many pages it returns false. The link to hasAttribute was also broken, and now goes to MDN.
How do you change a page with JavaScript?
Find the element with querySelector, then update text with textContent, styling with classList and child nodes with append and remove. Keep innerHTML for markup you trust.
The original post ended with a screenshot of setting the body background to blue and the text to white. Here it is as code, with the version I’d write now:
// The original example: blue background, white text
document.body.style.backgroundColor = "blue";
document.body.style.color = "white";
// What I’d write now: keep the colours in CSS and switch a class
// CSS: body.inverted { background: blue; color: white; }
document.body.classList.add("inverted");Inline styles work, but they scatter design decisions through your scripts. With a class, the CSS owns how things look and JavaScript only decides when.
The choice between textContent and innerHTML matters more. MDN calls innerHTML one of the most common vectors for cross-site scripting. Browsers don’t run <script> tags inserted this way, but there are plenty of other ways to get code to run:
const name = "<img src='x' onerror='alert(1)'>";
greeting.textContent = name; // shows the string as text. Safe.
greeting.innerHTML = name; // creates an <img> and runs the onerror codeIf the content is text, use textContent. If it really must be HTML from an outside source, sanitize it first.
For adding several nodes, build them and insert them in one call. append() takes any number of nodes, and a DocumentFragment does the same job when you’re building a larger subtree. MDN notes the performance benefit of fragments is often overstated, so choose whichever reads better.
const items = ["Apple", "Orange", "Banana"];
const nodes = items.map((item) => {
const li = document.createElement("li");
li.textContent = item;
return li;
});
document.querySelector("ul").append(...nodes);How do DOM events work?
You register a function with addEventListener, and the browser calls it when the event happens. Most events bubble up through the element’s ancestors, so one listener on a parent can handle events from all of its children.
That second part is called event delegation, and it’s the pattern I’d teach first after the basics. It keeps working when items are added later, and you don’t have to clean up a listener per row:
const list = document.querySelector("#todo");
list.addEventListener("click", (event) => {
const button = event.target.closest("button.remove");
if (!button) return;
button.closest("li").remove();
});event.target is the innermost element that was clicked, which may be an icon inside the button, so closest() walks up to the element you care about.
Do you still need the DOM if you use React?
You need to understand it, but you rarely touch it directly. React updates the DOM to match what your components render. When you do need the real node, to focus, scroll or measure, React gives you a ref.
The React documentation puts the rule plainly: avoid changing DOM nodes managed by React. Focusing an input is fine. Removing a node React rendered can break the next update, because React no longer knows what’s on the page.
import { useRef } from "react";
export function Search() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Search</button>
</>
);
}I covered how components and data fit together in React components, state and props, and when React updates the page in the React component lifecycle. Both make more sense once the DOM itself is familiar. Debugging a framework app still comes down to the elements panel, the event listeners and the tree.
If you’re learning this now with an AI assistant, ask it to explain why a snippet works, then type it into the console yourself. I wrote more about that in using AI to learn without offloading the thinking.
Sources
Checked in November against MDN’s DOM reference and learning pages, the WHATWG DOM Living Standard and the React documentation. The table and the examples are mine.
Short answers
What is the DOM in JavaScript?
The Document Object Model is an API to HTML and XML documents. The browser represents the page as a tree of objects, and JavaScript uses the DOM to read and change its content, structure and style. The DOM is a web API provided by the browser, not part of the JavaScript language.
Are all DOM nodes elements?
No. All elements are nodes, but text, comments, the document and the doctype are nodes too. The Node interface defines twelve nodeType constants, and the DOM Living Standard marks three of them (entity reference, entity and notation) as legacy.
Are attributes nodes in the DOM tree?
Not in the modern DOM. Attributes are Attr objects that inherit from Node, but they never have a parent or children and don’t appear in childNodes. You read and write them with getAttribute, setAttribute and hasAttribute on the element.
Should I use textContent or innerHTML?
Use textContent for text. innerHTML parses its value as HTML, so passing it an untrusted string can run attacker code through attributes such as onerror. Use innerHTML only with markup you trust or have sanitized.
Open the console
Open the developer tools on any page, select an element and try $0.classList, $0.childNodes and $0.textContent. Ten minutes of poking at a real tree teaches more than another diagram.