DOM
The DOM (Document Object Model) is the browser's tree of nodes for an HTML (or XML) document. JavaScript reads and changes the page by talking to that tree, not by editing the HTML file on disk.
Detailed Explanation
The HTML you shipped is parsed into a tree: a document, an html element, head, body, and everything inside. Each tag is an Element. Text is a Text node. The DOM is live. document.querySelector(".price").textContent = "9" changes what the user sees.
You find nodes with getElementById, querySelector / querySelectorAll, getElementsByClassName (live HTMLCollection), and traversal (parentElement, children, nextElementSibling). querySelectorAll returns a static NodeList. Live collections update when the tree changes; that surprises loops that insert siblings.
You create nodes with createElement, createTextNode, and cloneNode. You insert with append, prepend, before, after, replaceWith, or the older appendChild. You remove with remove(). innerHTML parses a string into children and is an XSS footgun if the string includes untrusted text. Prefer textContent for text and createElement for structure.
Layout is not free. Reading offsetHeight after writes can force a reflow. Batch DOM changes (build a fragment, then append once) or use the framework's renderer. The virtual DOM is a library strategy; the real DOM is still what the browser paints.
The DOM is a host API, not ECMAScript. Node does not have it unless you add JSDOM. Workers do not have it. document is undefined in those contexts.
What it costs you: leakage and XSS. Holding a node after you remove it keeps a detached tree. Putting user input in innerHTML runs scripts. Querying in a hot scroll handler without caching the node is wasted work.
Reach for the DOM when you write browser UI. Reach for a framework when the tree updates are complex. Reach for textContent whenever the value is data, not trusted markup.
Code Examples
const list = document.querySelector("#cart");
const item = document.createElement("li");
item.textContent = "book";
list.append(item);
const price = document.querySelector(".price");
price.textContent = "9.00";const frag = document.createDocumentFragment();
for (const name of ["a", "b", "c"]) {
const li = document.createElement("li");
li.textContent = name;
frag.append(li);
}
document.querySelector("ul").append(frag);Unsafe if `html` is user-controlled
// Unsafe if `html` is user-controlled
// el.innerHTML = html;
el.textContent = html; // shows the characters, does not parse tagsCommon Gotchas
`innerHTML` with untrusted strings is XSS
use `textContent` or a sanitiser.
Detached nodes stay in memory if JS still points at them
drop references on unmount.
`querySelector` returns `null`
always check before calling methods.