Intermediate 8 min
The DOM and browser events
The DOM is the browser’s tree of page elements, and events let your JavaScript respond to what happens there.
How it works
Select elements once the browser has made them available. The listener is a function you register now for the browser to call later. Updating textContent changes visible text without asking the browser to interpret that text as HTML.
Walk through an example
Select a button with querySelector and add a click listener. In the listener, set a status element’s textContent to update what the visitor reads.
What to watch for
A selector can return null. Confirm the element exists before using it, and prefer textContent for plain user-visible text.
Code example
const button = document.querySelector('#save');
const status = document.querySelector('#status');
if (button && status) {
button.addEventListener('click', () => { status.textContent = 'Saved'; });
}Check your understanding
What does querySelector return?
See the example and explanation
- Worked example
- Given
Selecting '#save' when the current page has no matching id. - Answer
null
No element matches the selector, so the browser returns null instead of an element object.