The DOM
The live, in-memory version of a page that the browser builds and JavaScript can read and change.
What is it?
The HTML you write is just text in a file: the starting instructions for a page, not the running page. When the browser loads it, it builds a separate, live version of the page in memory. That version is a tree of objects, one per element, each knowing its content, its attributes, and what's nested inside it.
This tree is the DOM (Document Object Model). The browser draws the page from it, and JavaScript changes it after the page loads: adding a list item, changing a heading's text, removing an element.
So editing the HTML file does nothing to a page that's already open, but changing the DOM does, because the DOM is what's being rendered. When you inspect an element in developer tools, you're seeing the live DOM, which may no longer match the HTML that was first sent.
Explain like I'm 10
The HTML file is a printed recipe. The DOM is the dish being cooked right now: you can add salt or swap an ingredient mid-cook, and the printed recipe on the counter doesn't change.
Examples
HTML source vs. the live DOM
<!-- original HTML file -->
<ul id="list">
<li>Apples</li>
</ul>
// JavaScript, run after the page loads
document.getElementById("list").innerHTML += "<li>Bananas</li>";The HTML file has one list item. After the script runs, the live DOM has two. The file's raw source still shows one, because the file never changed.
Reading and changing an element
const heading = document.querySelector("h1");
console.log(heading.textContent); // reads the current text
heading.textContent = "New Title"; // changes it livequerySelector finds a node in the DOM tree. JavaScript can then read its current state or assign new values, and the page updates right away.
How it works
As the browser parses HTML, it creates a node object for each tag and attaches it to a tree, nested the same way the tags were. Each node has properties (tag name, attributes, text, children) and methods JavaScript can call to read or change them.
Because the DOM is just objects in memory, any change (adding a node, deleting one, changing text) shows on screen almost immediately, with no reload.
HTML source (text)
|
| browser parses it
v
DOM tree (live objects in memory)
|
|<--- JavaScript reads/writes here
v
Rendered page on screenWhy does it exist?
Pages need to change after they load, without the browser re-fetching and re-parsing the whole HTML file for every small update. A tree of live, addressable objects gives JavaScript an efficient way to inspect and change exactly the parts that need it.
When to use it
Whenever JavaScript reads or changes what's on a page (showing a new element, hiding something, updating text after fetching data), it does so through the DOM, not by editing HTML files.
When not to use it
If content never changes after the page loads, skip DOM scripting; plain HTML and CSS are simpler and faster. For large interfaces that change often, a framework that manages DOM updates efficiently is usually better than doing it all by hand.
Common mistakes
Confusing 'view page source' (the original HTML from the server) with the live DOM in the developer tools inspector. They can differ after scripts run.
Assuming that editing the HTML file will change a page already open in a browser tab.
Querying the DOM for the same element over and over in a loop instead of looking it up once and reusing it.
Practice exercises
- Easy:
Use document.querySelector to select an element on a page and log its text content to the console.
- Medium:
Write a script that adds a new paragraph to the page after it loads. Explain why 'view page source' wouldn't show it.
- Hard:
In your own words, explain the difference between the DOM and HTML. Describe one situation where mixing them up would lead to a debugging mistake.
Interview questions
What is the DOM?
The Document Object Model: a live, in-memory tree of objects for the page's current structure. The browser builds it from the HTML, renders from it, and lets JavaScript read and change it.
How is the DOM different from the original HTML source?
The HTML source is static text describing the page's starting state. The DOM is a live version built from that text. JavaScript can change it after the page loads, while the HTML file stays the same.
Why can JavaScript change what's on screen without reloading the page?
It edits the live DOM tree directly (adding, removing, or changing nodes in memory), and the browser re-renders from the tree's current state, not from the original HTML file.
What's the difference between `textContent` and `innerHTML`, and why does it matter for security?
textContent treats what you assign as plain text and escapes any markup. innerHTML parses the string as HTML and creates real elements. Inserting untrusted user input through innerHTML can let attacker-supplied <script> or event-handler markup run, a bug class known as XSS.
What's the difference between `document.getElementById`, `document.querySelector`, and `document.querySelectorAll`?
getElementById finds one element by its id without evaluating a CSS selector, and is the fastest. querySelector takes any CSS selector and returns the first match. querySelectorAll takes a CSS selector and returns all matches as a NodeList.
Is the NodeList returned by `querySelectorAll` live or static? What about `getElementsByClassName`?
querySelectorAll returns a static snapshot: matching elements added later won't appear in it. getElementsByClassName (and getElementsByTagName) return a live HTMLCollection that updates automatically as matching elements are added or removed.
What's the difference between a DOM 'node' and an 'element'?
Node is the general category. It includes element nodes, text nodes (the text between tags), and comment nodes. An element is a node created from an HTML tag, like <div> or <p>. Not every node is an element.
How would you move from a child element to its parent, and to its next sibling, in the DOM?
element.parentElement (or parentNode) gives the containing element. element.nextElementSibling and previousElementSibling move to neighboring elements at the same level, skipping text and comment nodes.
What's the difference between `element.children` and `element.childNodes`?
children returns only child elements. childNodes returns every child node, including whitespace-only text nodes from the line breaks and indentation in your HTML. That's why childNodes.length is often larger than you expect.
How do you create a brand-new element and add it to the page with JavaScript?
document.createElement("li") creates a detached element that isn't on the page yet. parent.appendChild(newElement) (or insertBefore for a specific position) attaches it to the live DOM, and the browser renders it.
What actually happens when you set `element.innerHTML = ""`?
The browser removes every descendant node of that element, including any event listeners attached to them. An empty string parses to no content, so nothing replaces them.
What is event bubbling?
When an event fires on an element, it runs that element's handlers and then moves upward, running matching handlers on each ancestor in turn up to the document, unless something stops it.
What is event delegation, and why does bubbling make it possible?
Instead of a click handler on every list item, you put one handler on their shared parent and check event.target to see which item was clicked. It works because a click on any descendant bubbles up to the parent's handler.
Given `<div id="outer"><button id="btn">Click</button></div>` with click listeners on both `#outer` and `#btn`, and no `stopPropagation` anywhere, what order do the handlers run in when the button is clicked?
#btn first, then #outer. Bubbling-phase handlers fire from the target outward to its ancestors.
What's the difference between `event.stopPropagation()` and `event.preventDefault()`?
stopPropagation() stops the event from moving on to other handlers (bubbling up or capturing down) but leaves the browser's default behavior alone. preventDefault() cancels the default action, like following a link or submitting a form, but the event still reaches other handlers.
Why does repeatedly calling `document.querySelector` for the same element inside a loop hurt performance?
Each call searches (part of) the DOM tree again. If the element doesn't change between iterations, look it up once outside the loop and reuse the reference.
What's the difference between `appendChild` and `append`?
appendChild takes exactly one Node and returns it. The newer append takes multiple arguments, including plain strings, and returns undefined. It's more flexible, but can't be used where you need appendChild's return value.
A `<script>` at the top of `<head>` runs `document.querySelector("#footer")` and gets `null`, even though `<div id="footer">` clearly exists further down in the `<body>`. Why?
The browser builds the DOM top to bottom as it parses. A script in <head> runs before the parser reaches the <body>, so #footer doesn't exist in the DOM yet.
How does adding `defer` to a `<script>` tag relate to that problem?
defer lets the browser keep parsing and building the DOM without waiting for the script, then runs the script after parsing finishes. By then, every element in the HTML is already in the DOM.
What is a `DocumentFragment`, and why use one before inserting many nodes into the DOM?
It's a lightweight container outside the visible DOM tree. You build a batch of nodes in it, then append the whole fragment in one operation, so the browser updates the live page once instead of once per node.
You need to render 100 new list items from fetched data — why is calling `list.appendChild(item)` 100 times in a loop, directly on the live list, less efficient than building the items off-DOM first and inserting them all at once?
Each appendChild on an element that's already rendered can make the browser recompute layout and repaint. Building the nodes in memory (or a DocumentFragment) and inserting them in one call means that work happens once instead of up to 100 times.
Why is toggling a CSS class with `classList.add`/`classList.remove` often preferred over setting `element.style` properties directly?
classList keeps visual values in CSS, where they can be reused, and switches a whole group of styles on or off in one call. Setting element.style hardcodes values into JavaScript one at a time, which is harder to keep consistent and mixes styling into your logic.