JavaScript: DOM

The DOM (Document Object Model) is the tree-like structure the browser creates from your HTML. JavaScript uses it to find elements, change content, and respond to events.

What you will learn

HTML, DOM, and the screen

HTML is the document source. The browser reads it and builds a tree of nodes: elements such as button, text, and their parent-child relationships. The DOM is this structure, not the pixels on the screen. CSS controls appearance, while JavaScript can update the DOM.

A small example

<p id="message">Waiting...</p>
<button id="change">Change message</button>
const message = document.querySelector('#message');
const button = document.querySelector('#change');

button.addEventListener('click', () => {
  message.textContent = 'The DOM was updated.';
});

querySelector finds an element using a CSS selector. textContent changes its text, and addEventListener runs a function when an event occurs.

Think in four steps

  1. Find the element.
  2. Read or change its content, attributes, or classes.
  3. Listen for an event when the change should happen.
  4. Check the result with keyboard and screen-reader use in mind.

Common mistakes