{"canonical_url":"https://engineer.company/glossary/dom/","content_markdown":"# DOM\n\n## What it is\n\nThe DOM, short for Document Object Model, is the tree of objects a browser\nbuilds from a page and keeps in memory for as long as the page is open. The HTML\nparser reads the markup, and its output is a document object: every element,\nevery run of text and every comment becomes a node, and each node knows its\nparent, its children and its neighbours. Scripts read and change the page\nthrough that tree, and what the browser draws is worked out from it.\n\nThe WHATWG maintains the model in the DOM Standard, whose own summary names\nthree things it covers without tying them to any one platform: node trees,\nevents, and the aborting of activities in progress. The name is older than the\nstandard. In its original sense it meant an interface for reaching into a\ndocument and changing it; today most people also say “the DOM” for the tree\nitself, and both meanings are in daily use. The HTML Standard builds on top of\nit: HTML defines the elements and what they do, the DOM Standard defines what a\nnode, an element, an attribute and an event are.\n\nThe tree is not the source file. A page's HTML is text that arrived over the\nnetwork. The DOM is what the parser made of that text, with every parse error\nhandled by rules the HTML Standard spells out, and then changed by every script\nthat has run since. The parser keeps details that are easy to forget. The\nwhitespace between two tags can become a text node of its own, so the first\nchild of an element is not always the first element inside it, although the\nstandard's own example notes that not every stretch of whitespace turns into a\ntext node.\n\nNodes come in a handful of kinds. The document sits at the root, with a doctype,\nelements, text nodes and comments beneath it. A document fragment is a light\ncontainer that sits outside the page's tree, which makes it a handy place to\nassemble a block before inserting it in one move. An element can also host a\nshadow tree, a separate tree of its own that the document's ordinary queries do\nnot reach into.\n\nLists of nodes come in two kinds, and the difference matters. The standard's\nrule is that a collection is live unless stated otherwise: `childNodes` and the\nHTMLCollection from `getElementsByClassName()` change as the tree changes.\n`querySelectorAll()` is the stated exception and returns a static list, a\nsnapshot taken at the moment of the call.\n\nThe same standard defines how events travel. An event is dispatched at a target\nnode and passes through three phases: capturing, on the way down from the top of\nthe tree through the target's ancestors; at the target itself; and bubbling,\nback up through the ancestors. The `eventPhase` property reports where it is,\nas 1, 2 or 3, and 0 when the event is not being dispatched. A listener added\nwith `addEventListener()` takes options: `once` removes it after its first call,\n`passive` promises that it will not call `preventDefault()`, and `signal` ties\nit to an `AbortController`, so that aborting the controller removes the\nlistener.\n\n## Why it matters\n\nEvery script that changes a page works through the DOM, whatever language or\nframework it was written in. A framework adds a layer of its own on top, but\nwhat the reader finally sees is nodes in this tree. Next.js describes hydration\nas React attaching event handlers to the DOM, which is how HTML sent from the\nserver becomes a page that responds to clicks. A team that knows the tree\nunderneath can debug what the framework actually did, rather than what it was\nasked to do.\n\nThe tree is also where text and markup part ways. A string assigned to\n`textContent` replaces an element's children with a single text node and is\nnever read as markup. The same string assigned to `innerHTML` is handed to the\nHTML parser, and the HTML Standard notes that those setters remove nothing\ndangerous by default. Which of the two a page uses decides whether a visitor's\ndisplay name is shown as text or run as code.\n\nWhat a reader experiences depends on more than the tree. Styles decide whether\na node is visible, where it sits and whether a pointer can reach it, and none of\nthat is visible to a tool that only walks the nodes. That gap is where automated\nchecks are most often wrong, and it is the reason to test a page as rendered as\nwell as the document behind it.\n\nFinally, the DOM is the contract between a page and everything that reads it\nafter the server has finished. Tests that click through a page, browser\nextensions and assistive software all start from the live tree. The other side\nof that contract is easy to miss: a crawler that does not run JavaScript sees\nonly the HTML that was sent, and none of the nodes that scripts add later.\n\n## What it looks like in practice\n\nThe script below, written for this article, fills a list of orders from data,\nkeeps a single click listener on the list rather than one per item, and can\nremove that listener later with one call. `openOrder` stands for whatever the\npage does when an order is chosen.\n\n```js\nconst list = document.querySelector(\"#orders\");\nconst controller = new AbortController();\n\nfunction render(orders) {\n  const items = orders.map((order) =\u003e {\n    const li = document.createElement(\"li\");\n    li.dataset.id = order.id;\n    li.textContent = `${order.number}: ${order.status}`;\n    return li;\n  });\n  list.replaceChildren(...items);\n}\n\nlist.addEventListener(\n  \"click\",\n  (event) =\u003e {\n    const li = event.target.closest(\"li\");\n    if (li) openOrder(li.dataset.id);\n  },\n  { signal: controller.signal },\n);\n\n// When the view goes away:\ncontroller.abort();\n```\n\nEach part maps onto the standard. `createElement()` makes an element that\nbelongs to no parent until it is inserted. `textContent` puts the order number\nin as text, so a status that happens to contain angle brackets stays a status.\n`replaceChildren()` removes the old items and inserts the new ones in a single\noperation. The one listener on the list serves every item because a click on an\nitem bubbles up to the list, and `closest()` walks from whatever was clicked to\nthe nearest `li`. Aborting the controller removes the listener without the page\nhaving to keep a reference to the function.\n\nThe tree also explains a class of defects that this site's own review turned up.\nIn\n[an accessibility review carried out in August 2026](/portfolio/the-accessibility-faults-your-checker-misses/),\nthe site passed its automated rules and still had eleven defects, every one of\nthem down to how the page rendered rather than to what its markup said. Eight\nfooter links stayed in the tab order behind `pointer-events`, a property that\nremoves pointer interaction and nothing else. To anything reading the document\nthey were ordinary links; a pointer never reached them, and the keyboard still\nstopped on every one. A scroll-driven animation clipped the footer off three\npages. Of the four rules the review left behind, one reads as a warning against\ntrusting the tree alone: visibility has to be established from the rendered\npixels, not merely from the document tree.\n\n## Where it goes wrong\n\n**A loop over a live collection skips every other item.** The HTMLCollection\nfrom `getElementsByClassName()` is live, so a loop that removes the class from\neach element by index shrinks the collection under itself and steps over every\nsecond element. Iterate a static list instead: `querySelectorAll()` returns one,\nand `Array.from()` turns a live collection into a plain array first.\n\n```js\nconst pending = document.getElementsByClassName(\"pending\");\nfor (let i = 0; i \u003c pending.length; i++) {\n  pending[i].classList.remove(\"pending\"); // skips every other one\n}\n\nfor (const el of document.querySelectorAll(\".pending\")) {\n  el.classList.remove(\"pending\"); // static list: all of them\n}\n```\n\n**Listeners pile up.** A view that adds its listeners every time it renders, and\nnever removes them, runs each handler once per render: after three visits, one\nclick sends three requests. Removing a listener by hand takes the very same\nfunction object that was added, and an arrow function written inline at the call\nleaves nothing to pass back. Pass a `signal` from one `AbortController` per\nview, as in the example above, and a single `abort()` removes every listener the\nview added; use `once: true` for a listener that should fire only one time.\n\n**Text goes in as markup.** Building a string of HTML from data and assigning it\nto `innerHTML` gives the data to the parser, with no sanitizing by default. A\ndisplay name that carries markup, an image tag with an error handler for\ninstance, arrives on the page as a real element with its handler attached. Text\nbelongs in `textContent` or in a text node made with `createTextNode()`. Where\nmarkup really must come from a string, the HTML Standard defines `setHTML()`,\nwhich sanitizes as it parses and removes unsafe content.\n\n**An observer feeds itself.** A `MutationObserver` reports changes to the nodes\nit watches, and its callback runs after each batch of changes. A callback that\nwrites to the subtree it observes, to add a counter or correct a class, creates\nnew records and is called again, and the page can lock up in a loop of its own\nmaking. Watch only what has to be watched, with `attributeFilter` and without\n`subtree` where possible, have the callback check whether its change is already\nin place before writing, or call `disconnect()` before the write and\n`observe()` again after it.\n\n## Further reading\n\n- [DOM Standard](https://dom.spec.whatwg.org/) — the WHATWG's definition of\n  nodes, trees, live and static collections, events, `AbortController` and\n  `MutationObserver`.\n- [Parsing HTML documents](https://html.spec.whatwg.org/multipage/parsing.html)\n  — how the HTML parser turns a stream of characters into a document object,\n  parse errors included.\n- [Dynamic markup insertion](https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html)\n  — `innerHTML`, `setHTML()` and `setHTMLUnsafe()`, and which of them\n  sanitize.\n- [Server and Client Components](https://nextjs.org/docs/app/getting-started/server-and-client-components)\n  — the Next.js account of hydration: HTML from the server, then event handlers\n  attached to the DOM.\n\n\u003chttps://engineer.company/glossary/dom/\u003e\n","date_modified":"2026-10-30T02:51:31Z","description":"The tree of nodes a browser builds from HTML: what the DOM Standard defines, live and static lists, how events travel, and four ways scripts trip over it.","formats":{"gemtext":"https://engineer.company/glossary/dom/index.gmi","gopher":"https://engineer.company/glossary/dom/gophermap","html":"https://engineer.company/glossary/dom/","json":"https://engineer.company/glossary/dom/index.json","markdown":"https://engineer.company/glossary/dom/index.md","pdf":"https://engineer.company/glossary/dom/index.pdf"},"kind":"page","language":"en","title":"What is the DOM?","url":"https://engineer.company/glossary/dom/","version":1}