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
- How HTML becomes a DOM tree
- How JavaScript finds and updates an element
- How to insert text safely and make updates understandable
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
- Running code before the target element exists; use a script with
deferor wait for the document. - Replacing meaningful content without updating accessible names or status text.
- Using
innerHTMLwith untrusted input and creating an injection risk.