What is the DOM?
The DOM (Document Object Model) is the browser's in-memory tree representation of an HTML document, plus the API JavaScript uses to read and change it. The browser parses HTML into nodes (document, elements, text, comments); changes made to the DOM through JavaScript are what update what users see.
Key ideas
- Tree of nodes:
document→<html>→<head>/<body>→ elements and text nodes. Each node has a parent, children and siblings. - The DOM is not the HTML source: the parser fixes invalid markup (inserting
<tbody>, closing tags), and scripts can change it at any time. "View source" shows the original HTML; DevTools' Elements panel shows the live DOM. - Live API:
querySelector,createElement,append,remove,classList,textContent,addEventListener.
Rendering pipeline
DOM + CSSOM → render tree → layout (geometry) → paint → composite. Changing layout properties triggers reflow, which is why batching DOM reads and writes matters for performance.
Events
Events travel through the tree: a capture phase down to the target, then a bubble phase back up. Bubbling is what makes event delegation possible.
Related concepts
- Virtual DOM (React): a JavaScript description of the UI that React diffs to compute the minimal real DOM updates.
- Shadow DOM: an encapsulated subtree used by Web Components.
- Accessibility tree: derived from the DOM, used by assistive technologies.
Interview tip
Distinguish the DOM from HTML source and from the virtual DOM; interviewers often probe that difference.
Code example
1<ul id="list"><li>Learn HTML</li></ul>2<button id="add">Add item</button>3<pre id="tree"></pre>4<script>5 const list = document.getElementById("list");67 // Build new nodes and insert them in one operation8 document.getElementById("add").addEventListener("click", () => {9 const frag = document.createDocumentFragment();10 for (const text of ["Learn CSS", "Learn the DOM"]) {11 const li = document.createElement("li");12 li.textContent = text; // safe: never parses HTML13 frag.append(li);14 }15 list.append(frag);16 printTree();17 });1819 // Walk the live DOM tree20 function printTree(node = list, depth = 0, out = []) {21 const label = node.nodeType === Node.TEXT_NODE ? `"${node.textContent}"` : `<${node.nodeName.toLowerCase()}>`;22 out.push(" ".repeat(depth) + label);23 node.childNodes.forEach((c) => printTree(c, depth + 1, out));24 document.getElementById("tree").textContent = out.join("\n");25 return out;26 }27 printTree();28</script>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.