DOM & events
Build an interactive widget with vanilla JS and event listeners.
By Invicly Tech, , in Frontend with React & Next.js. About 8 minutes to read.
In short
The DOM is the browser's tree of objects representing the page. JavaScript selects elements, changes them and listens for events like clicks to make pages interactive.
Explained simply
When a browser loads HTML, it builds a live model of the page in memory called the DOM (Document Object Model). Each tag becomes an object, a node, in a tree. JavaScript can read and change that tree, and the screen updates to match.
So the DOM is the bridge between your code and what people see. Want to change some text? Find the node and set its textContent. Want a new list item? Create an element and append it. Want to hide a panel? Toggle a class.
Events are how the page tells your code that something happened: a click, a key press, a form submit, the page finishing loading. You attach a listener, which is a function the browser calls when that event fires.
Think of the DOM as a puppet and events as the strings pulled by the user. Your listener feels the pull and moves the puppet. Frameworks like React do this for you behind the scenes, but knowing the raw version makes their behavior much easier to understand.
Press Play on a diagram to walk through it one step at a time.
- Step 1Capture phase
Event travels down from window to the target
- Step 2Target phase
Listeners on the clicked element run
- Step 3Bubble phase
Event travels back up through each ancestor
- Step 4Delegated handler
A parent listener checks event.target and reacts
- html
- head
- body
- body
- h1 (element node)
- ul#todo
- button.add
- ul#todo
- li
- li
- li
- li
- "Buy milk" (text node)
- User to li > button: Clicks Delete on item 31Clicks Delete on item 3
- li > button to ul listener: Click bubbles up to the ul2Click bubbles up to the ul
- ul listener to Your code: Calls handler with event3Calls handler with event
- Your code to li > button: target.closest("li") finds the item4target.closest("li") finds the item
- Your code to ul listener: Removes that li from the list5Removes that li from the list
In depth
Finding and changing elements
document.querySelector(selector) returns the first element matching a CSS selector, or null. querySelectorAll returns a static list of all matches that you can loop over with forEach or for...of.
To change content, prefer textContent, which inserts plain text safely. innerHTML parses a string as HTML, which is handy for trusted templates but dangerous with user input, because a value like an img tag with an onerror attribute could run script. For classes, use element.classList.add, remove and toggle instead of rewriting className. For data, use data- attributes, read through element.dataset.
- querySelector returns one element or null
- textContent for user data, never innerHTML
- classList.toggle("open") to show and hide
- dataset.id reads data-id
Capture, target, bubble
An event travels in three phases. First it goes down from the window to the clicked element (capture). Then it reaches the element itself (target). Then it bubbles back up through every ancestor. By default, listeners run during bubbling.
event.target is the deepest element that was actually clicked, maybe an icon inside a button. event.currentTarget is the element whose listener is running now. element.closest(selector) walks up from target to find the nearest matching ancestor, which is the key tool for delegation.
event.stopPropagation() stops bubbling, but use it rarely, because other code may depend on the event reaching it.
Default actions
Some events have a built-in browser action. Clicking a link navigates. Submitting a form reloads the page with a request. Pressing Space scrolls. event.preventDefault() cancels that default so your code can handle it, for example submitting a form with fetch instead.
Read form values with new FormData(form), which collects every named field. Listen for submit on the form, not click on the button, so pressing Enter in a field also works.
- User to Form: Presses Enter in a field1Presses Enter in a field
- Form to Submit handler: submit event2submit event
- Submit handler to Form: preventDefault(): no page reload3preventDefault(): no page reload
- Submit handler to Server: fetch with new FormData(form)4fetch with new FormData(form)
- Server to Submit handler: Response5Response
- Submit handler to User: Shows the result on the page6Shows the result on the page
Doing DOM work efficiently
Each change to the DOM can make the browser recalculate layout. Changing many things one by one is fine for small pages, but adding 1,000 list items one at a time is slow. Build them in a DocumentFragment or an array of elements, then append once with append(...items).
Also avoid reading layout (like offsetHeight) right after writing styles in a loop, because it forces the browser to lay out the page again each time.
- 1,000 separate DOM changes
- Layout may be recalculated often
- Slow on big lists
- Build items off the page
- append(...items) once
- One change to the live DOM
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Select and create DOM elements~1h
- 2Handle events with addEventListener~1h
- 3Use event delegation~1h
- 4Build an interactive widget in vanilla JS~1h
Key points
- querySelector and querySelectorAll find elements using CSS selectors.
- addEventListener attaches handlers without overwriting existing ones.
- Most events bubble, so one parent listener can handle many children.
- Use textContent for plain text to avoid injecting unsafe HTML.
Key terms
Tap a card to flip it. 0/5 known
Examples
const list = document.querySelector('#todos');
const input = document.querySelector('#new-todo');
document.querySelector('#add').addEventListener('click', () => {
const li = document.createElement('li');
li.textContent = input.value;
list.append(li);
input.value = '';
});
list.addEventListener('click', (event) => {
if (event.target.matches('li')) event.target.classList.toggle('done');
});Creating elements and one delegated listener for every item.
A character counter for a textarea
A tweet box allows 280 characters. Step 1: select the textarea and the counter paragraph. Step 2: listen for the input event, which fires on every change, including paste. Step 3: compute remaining characters and write them with textContent. Step 4: toggle a warning class when fewer than 20 are left so CSS can turn it red.
const box = document.querySelector("#tweet");
const counter = document.querySelector("#left");
box.addEventListener("input", () => {
const left = 280 - box.value.length;
counter.textContent = left + " characters left";
counter.classList.toggle("warn", left < 20);
});Submitting a form without a page reload
Step 1: listen for submit on the form. Step 2: call preventDefault so the browser does not reload. Step 3: collect the fields with FormData and turn them into a plain object. Step 4: send them with fetch and show a message. Listening on submit means pressing Enter works too.
const form = document.querySelector("#contact");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(form));
await fetch("/api/contact", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
form.reset();
document.querySelector("#status").textContent = "Thanks, message sent!";
});Quick reference
- document.querySelector(".card") returns the first match or null
- el.textContent = value is safe; el.innerHTML = userValue is not
- el.classList.toggle("open", condition) adds or removes by condition
- event.target = what was clicked; event.currentTarget = element with the listener
- event.target.closest("li") finds the nearest matching ancestor
- Listen to submit on forms and call event.preventDefault()
- Object.fromEntries(new FormData(form)) gives a plain object of fields
- Put scripts at the end of body or use the defer attribute
Common mistakes
- Using innerHTML with user input, which allows script injection.
- Adding a listener to each list item instead of delegating to the parent.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Make a button with id "theme" toggle a class "dark" on the body each time it is clicked.
- Exercise 2medium
Given an array of fruit names, render them as li elements into ul#fruits using a single append call.
- Exercise 3hard
Build tabs: buttons with data-tab="a", "b", "c" inside div.tabs, and panels with ids a, b and c. One listener on .tabs should show the matching panel and hide the others.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between the DOM and HTML?
- HTML is the text file you write. The DOM is the live tree the browser builds from it, which JavaScript can change without touching the original file.
- Why does my listener not work on items I add later?
- If you attached listeners to each item at the start, new items never got one. Use event delegation: one listener on the parent handles current and future children.
- Do I still need to learn DOM APIs if I use React?
- Yes, at least the basics. React manages the DOM for you, but refs, events, focus handling and debugging all rely on knowing what the DOM is doing.