The DOM (Document Object Model) is a programming interface that represents an HTML or XML document as a structured tree of objects, allowing code to read and manipulate page content, structure, and styles dynamically.
The DOM is a language-agnostic, cross-platform API defined by the W3C that turns a static HTML document into a live, in-memory object tree. Each HTML element, attribute, and piece of text becomes a 'node' in that tree. This lets programs — most commonly JavaScript — interact with a webpage as structured data rather than as raw text.
When a browser receives an HTML file, its HTML parser reads the markup top-to-bottom and constructs the DOM tree before rendering the page. Tags become Element nodes, text content becomes Text nodes, and comments become Comment nodes. The root of every DOM tree is the 'document' object, and the outermost HTML element becomes its first child.
JavaScript accesses the DOM through the global 'document' object using methods like 'document.getElementById()', 'querySelector()', and 'querySelectorAll()'. Once you have a reference to a node, you can read or change its text, attributes, CSS classes, and styles, or append and remove child nodes entirely. These mutations are reflected in the browser immediately without reloading the page.
The DOM is not the same as the original HTML source file — it is a live representation that can differ significantly from it. JavaScript, browser error-correction (e.g. adding a missing tbody to a table), and dynamic frameworks all mutate the DOM after the initial parse. Always inspect the DOM via browser DevTools rather than assuming it matches your source HTML exactly.
Every time you read layout-sensitive properties (like 'offsetHeight') after writing to the DOM, the browser must recalculate layout in a process called a reflow, which is expensive. Batch your DOM reads and writes separately, or use techniques like DocumentFragment to build subtrees off-screen before inserting them. Modern frameworks like React use a Virtual DOM to minimise direct DOM mutations and reduce reflow costs.
© RM Full Stack & AI Engineer · All guides · Roadmaps · Open the app