Developer & Network Tools

The DOM Explained

Learn how browsers turn HTML into a tree of objects and how JavaScript reads and changes it.

Key takeaways

  • The DOM is a tree: each element, piece of text and comment is a node with a parent and possibly children.
  • Scripts find elements with selectors, then read or change their text, attributes and classes.
  • Use textContent for untrusted text; feeding it to innerHTML can let attackers run script.
  • Events travel through the tree, which allows one listener on a parent to serve many children.
  • The live DOM can differ from the original HTML source.

The DOM, or Document Object Model, is the browser's live representation of a web page as a tree of objects. The browser builds it from your HTML, draws the screen from it, and lets JavaScript read and change it. When a script adds a message, opens a menu or updates a price without reloading, it's changing the DOM.

HTML is the text you send. The DOM is what the browser makes of it, and the two can differ.

From text to tree

Take this small document:

<body>
  <h1>Shopping list</h1>
  <ul id="items">
    <li>Milk</li>
    <li>Bread</li>
  </ul>
</body>

The browser parses it into nodes. body has two element children, h1 and ul. The ul has two li children, and each li holds a text node.

The list element and its neighbors in the tree
ul#items One element node Attribute: id Describes this element Child: li Bread Second list item Parent: body The element that contains it Sibling: h1 Shares the same parent Child: li Milk First list item ul#items One element node Parent: body The element that contains it Sibling: h1 Shares the same parent Child: li Milk First list item Child: li Bread Second list item Attribute: id Describes this element

Words like parent, child and sibling come straight from this tree shape. Line breaks and indentation in your source also become text nodes, which can surprise you when walking nodes one by one. Properties such as children return only elements.

The parser also repairs mistakes. If you leave out tbody in a table, the browser adds it. If you nest elements in ways the rules don't allow, it rearranges them. That's one reason a selector based on your source may not match.

The document object

In JavaScript, the entry point is document. You can try these in the console of browser developer tools on any page:

document.title
document.querySelector("h1")
document.querySelectorAll("#items li")
document.getElementById("items")

querySelector takes a CSS selector and returns the first match, or null if there is none. querySelectorAll returns all matches as a static list. Some older methods, such as getElementsByClassName, return live collections that change as the page changes, which can confuse loops that add or remove items.

Calling a method on null is among the most common errors. It usually means the selector is wrong or the script ran before the element existed.

Reading and changing elements

Once you hold an element, you can change it:

const heading = document.querySelector("h1");
heading.textContent = "Groceries";
heading.classList.add("highlight");
heading.setAttribute("data-count", "2");

To add a new item:

const list = document.querySelector("#items");
const item = document.createElement("li");
item.textContent = "Apples";
list.append(item);

And to remove one:

list.querySelector("li").remove();

Prefer toggling classes over setting many inline styles. It keeps appearance in CSS and behavior in JavaScript.

textContent and innerHTML

Both can change what's inside an element, but they treat input very differently. textContent inserts plain text; any angle brackets appear on screen as characters. innerHTML parses the string as HTML and creates elements from it.

If that string includes text from users, a URL or another system, innerHTML can create elements that run code in your visitors' browsers. This is cross-site scripting. Use textContent for text, build elements with createElement, and when you really must accept formatted HTML, pass it through a well-maintained sanitizer. A Content Security Policy adds a further layer of protection.

How should you insert content?
Is it plain text, including anything a user typed? YES Assign it to textContent. 1 NO Is it a structure your own code defines? YES Create elements and set their text and attributes. 2 NO Must you show formatted HTML from elsewhere? YES Sanitize it with a trusted library before inserting. 3 NO Reconsider Avoid building HTML strings from data you do not control. Is it plain text, including anything a user typed? 1 IF YES Assign it to textContent. NO Is it a structure your own code defines? 2 IF YES Create elements and set their text and attributes. NO Must you show formatted HTML from elsewhere? 3 IF YES Sanitize it with a trusted library before inserting. NO Reconsider Avoid building HTML strings from data you do not control.

Events

The DOM also delivers events: clicks, key presses, form submissions and more. You register a function to run when one happens.

const form = document.querySelector("form");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  // handle the data here
});

preventDefault stops the browser's normal action, here a full page submission.

Most events bubble: after reaching the element where they happened, they travel up through its ancestors. That enables a technique called delegation. Instead of adding a listener to every list item, add one to the list:

list.addEventListener("click", (event) => {
  const li = event.target.closest("li");
  if (li) li.classList.toggle("done");
});

It works for items added later, too.

The journey of a click on a list item
1 Capture phase The event travels down from the top of the document toward the target. 2 Target It reaches the element that was clicked. 3 Bubble phase It travels back up through each ancestor. 4 Default action Unless prevented, the browser does what it normally would. Capture phase The event travels down from the top of the document toward the target. 1 Target It reaches the element that was clicked. 2 Bubble phase It travels back up through each ancestor. 3 Default action Unless prevented, the browser does what it normally would. 4

Forms and user input

Forms are where many scripts meet the DOM. Each field's current content is available through its value property, which can differ from the value attribute in the HTML. The attribute records the starting value; the property reflects what the person has typed. Checkboxes use checked in the same way.

To gather a whole form at once:

const data = new FormData(form);
const email = data.get("email");

Fields need a name attribute to be included. Browsers also offer built-in validation through attributes such as required, type="email" and maxlength, which give users quick feedback with no script. Treat it as convenience only. The server still has to check everything it receives.

Walking the tree

Sometimes you start from one element and need a relative. parentElement moves up one level, children lists element children, and nextElementSibling moves sideways. closest(selector) searches upward from an element, including itself, for the first match. matches(selector) tests whether an element fits.

Long chains such as three parents up and two siblings across break the moment someone adjusts the layout. A class or a data- attribute placed for the script's use is sturdier. Values in data- attributes appear under the element's dataset property, and they're always strings, so convert numbers before doing arithmetic.

Watching for changes

When something else modifies the page, such as a third-party widget, a MutationObserver can notify your code of added nodes or changed attributes. IntersectionObserver reports when an element scrolls into view, which is useful for loading content only as it's needed. Both are more efficient than checking repeatedly on a timer. Disconnect observers when you no longer need them.

When scripts run

A script that runs before the browser has parsed an element can't find it. For external scripts, the defer attribute downloads in parallel and runs after parsing finishes:

<script src="app.js" defer></script>

Scripts marked type="module" are deferred by default. You can also listen for the DOMContentLoaded event. An async script runs as soon as it arrives, in no guaranteed order, which suits independent code only.

Performance

Changing the DOM can force the browser to recalculate styles and layout and repaint. How a browser turns code into pixels describes that pipeline. A few habits help:

  • Build a batch of new elements first, then insert them together, for instance with a document fragment.
  • Avoid alternating between writing styles and reading sizes inside a loop, which forces repeated layout.
  • Keep very large pages manageable by loading or rendering long lists in portions.

Measure with the browser's performance tools before optimizing. Many pages never need it.

Frameworks and the DOM

Popular interface libraries let you describe what the screen should look like for a given state, and they update the DOM for you. Some keep an in-memory description and compare versions; others compile direct updates. Either way, the DOM is still what appears on screen, and understanding it makes framework errors far easier to read.

Web components add the shadow DOM, a separate subtree attached to an element with its own scoped styles. Ordinary selectors don't reach into it.

Accessibility

Assistive technology relies on a tree derived from the DOM. Real buttons, headings, labels and lists carry meaning that a clickable div doesn't. When script changes content, make sure keyboard focus stays sensible and important updates are announced, for example through live regions. Web accessibility gives the fundamentals.

Debugging DOM code

When a script doesn't do what you expect, check things in order. Is there an error in the console? Did the script load at all? Does your selector return an element when you type it into the console? Is the listener attached to the element you think, and does it still exist, or was it replaced by a later update?

Replacing a parent's contents with new HTML destroys the old child elements along with any listeners attached directly to them. The new ones look identical and do nothing. Delegating from a parent that stays in place avoids this.

Developer tools can pause execution when a particular element is modified, which finds the culprit when you can't tell which script keeps changing something. Menu names differ between browsers, so look for breakpoint options when you right-click a node in the inspector.

Common questions

Why is "view source" different from the inspector?

View source shows the HTML as delivered. The inspector shows the current DOM, after parser corrections, scripts and browser extensions have had their say.

Is the DOM part of JavaScript?

No. It's a web platform interface that browsers expose to JavaScript. Server-side JavaScript has no page DOM unless a library provides one.

Do changes survive a reload?

No. The DOM is rebuilt from the server's response. Save anything lasting on a server or in browser storage.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Developer & Network Tools →

Latest news on this topic