DOM: the Document Object Model

The DOM is the browser's tree-shaped representation of an HTML document. JavaScript can use it to find elements, change text, respond to actions, and build new content.

What you will learn

HTML becomes a tree

In <p>Hello</p>, the p element is a node and Hello is its text node. Parent and child relationships let the browser represent the document structure.

<p id="message">Hello</p>

Find and update an element

const message = document.querySelector('#message');
message.textContent = 'Hello from JavaScript';

textContent inserts text as text. When content comes from a user or an external source, prefer it over assigning untrusted strings to innerHTML.

React to an action

document.querySelector('#change').addEventListener('click', () => {
  document.querySelector('#message').textContent = 'Changed';
});

Make the result visible and keep keyboard users in mind when the action is triggered by a button or form.

Common mistakes