Bookmarks

DOM — Document Object Model

The programming interface of a web page: the browser represents the loaded document as a tree of nodes, and scripts find elements, change them and react to events.

Also: document tree, DOM tree

checked 9 Nov

All terms

The browser parses HTML and builds a tree of nodes from it: the DOM. From then on the page lives not as markup text but as an object model: scripts read and change nodes, and the browser immediately repaints the affected areas. That is why the DOM after loading rarely matches what was written in the HTML: the browser fixes tag nesting, and scripts add, remove and move nodes.

What the standard covers

The WHATWG standard describes not only the tree but also the behaviour of nodes:

  • node types: document, element, text, comment, document fragment and the attribute as a special node;
  • tree navigation and selection: getElementById, querySelector, querySelectorAll, closest;
  • tree modification: createElement, append, remove, replaceWith, textContent;
  • events: capture, target and bubbling, addEventListener and the event object;
  • shadow trees (shadow DOM): isolated subtrees inside an element.

The tree and collections

A page has a single tree root, the document; below it is the html element, containing head and body, then nested elements and text. Attributes are never child nodes: they belong to their element. A selector query returns a static list, while children or getElementsByTagName return a live collection that reflects changes to the tree by itself:

bash
const items = document.querySelectorAll('.item'); // static listconst list = document.querySelector('ul');list.append(document.createElement('li'));console.log(items.length, list.children.length); // 2 and 3

Standards and engines

The DOM was created so that one programming interface would work across different browsers and languages: the W3C published the first recommendation on 1 October 1998 (DOM Level 1), and Levels 2 and 3 added events, ranges and traversal. Today the WHATWG living standard applies: it evolves continuously, without numbered levels. It is implemented by the Chromium, WebKit and Gecko engines.

Sources

the term is written from these pages

Verified 9 Nov

Not to be confused with

what it is mixed up with and how it differs

  • SPAsingle-page application

    An SPA is an approach to building an application in which a framework keeps rebuilding the DOM on the client without reloading the page.

In depth in the references

where the topic is covered in detail