Free, independent guides since 2010

Code

The DOM explained: changing web pages with JavaScript

What the Document Object Model is, how browsers turn HTML into a tree of nodes, and how to select, change, create and remove elements and react to events with plain JavaScript.

<guide section="Code" type="guide" read="1 min"/>

The name of this website starts with “DOM” for a reason: the Document Object Model is the way programs see a document as a tree of nodes. In the browser, the DOM is what JavaScript reads and changes. (Java developers use the same idea for XML with dom4j.) This guide builds on modern JavaScript basics.

The page as a tree

HTML
<body>
  <main>
    <h1>Prices</h1>
    <ul id="prices"><li>Basic repair – €25</li></ul>
  </main>
</body>

The browser turns this into a tree: body contains main, which contains an h1 and a ul, which contains an li with text. You can inspect this tree in the Elements panel of your browser’s developer tools.

Selecting elements

JavaScript
const list = document.querySelector('#prices');
const items = document.querySelectorAll('#prices li');
const title = document.querySelector('main h1');

Changing content and style

JavaScript
title.textContent = 'Prices 2026';
list.classList.add('highlight');
list.setAttribute('aria-label', 'Price list');

Prefer textContent over innerHTML for user-supplied text: it cannot inject HTML or scripts.

Creating and removing elements

JavaScript
const li = document.createElement('li');
li.textContent = 'Full service – €65';
list.append(li);

items[0].remove();

Reacting to events

JavaScript
list.addEventListener('click', (event) => {
  const item = event.target.closest('li');
  if (item) item.classList.toggle('selected');
});

Listening on the parent and checking event.target (event delegation) works for items added later too.

Performance tips

  • Change classes instead of many individual styles.
  • Build many new elements in a DocumentFragment and add them at once.
  • Avoid reading layout values (like offsetHeight) in loops that also change the page.

Frequently asked questions

What is the difference between the DOM and HTML?

HTML is the text you write. The DOM is the live structure the browser builds from it, which JavaScript can change without reloading the page.

Is dom4j related to the browser DOM?

Conceptually yes – both represent documents as trees of nodes. The browser DOM is for HTML in web pages; dom4j is a Java library for XML documents.