DOM API
The DOM API lets JavaScript find and change the document tree that the browser created from HTML.
What you will learn
- How to find an element and update its content
- How events connect user actions to DOM changes
- When semantic HTML is better than custom JavaScript
A small flow
const message = document.querySelector('#message');
const button = document.querySelector('#change');
button.addEventListener('click', () => {
message.textContent = 'Updated';
});The script finds elements, listens for a click, and changes text. The browser then renders the updated DOM.
Choose the right operation
- Find
- Use selectors such as
querySelector()when you need an element. - Change text
- Use
textContentfor plain text. - Change attributes or classes
- Use DOM methods such as
setAttribute()orclassList. - Add or remove nodes
- Use methods such as
appendChild()andremove()when the structure must change.
Common mistakes
- Do not use JavaScript to recreate a native button, form, or disclosure control unnecessarily.
- Run code after the elements exist, or wait for the document to be ready.
- Use
textContentfor untrusted text rather than inserting it as HTML. - Make dynamic changes understandable to keyboard and assistive-technology users.