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
- Why the DOM is a useful model of the page
- How
document, elements, and text nodes relate - How selecting, changing, and listening to elements fit together
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
- Find the element.
- Read or change its content, attributes, or classes.
- Listen for an event when the change should happen.
- Check the result with keyboard and screen-reader use in mind.
Common mistakes
- Run DOM code after the elements exist, or wait for
DOMContentLoaded. - Use
textContentfor plain text; do not insert untrusted strings withinnerHTML. - Do not use JavaScript to replace semantic HTML or CSS when the browser already provides the right behavior.