The DOM and Events
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Select and update nodes safely without injecting markup.
- Explain event propagation and use delegation.
- Register and remove listeners without leaks.
Overview
#The document tree
The DOM is a tree of nodes. querySelector returns the first match and querySelectorAll returns a static list. createElement builds a node, and append or replaceWith inserts it. textContent sets plain text and is safe; innerHTML parses markup and can execute injected content, so it must never receive untrusted input.
const list = document.querySelector('#list');
const item = document.createElement('li');
item.textContent = 'New item';
list.append(item);
Event propagation
An event travels from the window down to the target in the capture phase, then bubbles back up. A listener runs in the bubbling phase unless capture is true. stopPropagation halts the trip and preventDefault cancels the browser's default action; they are different and should not be confused.
Delegation and cleanup
Attaching one listener to a container and reading event.target handles items added later and uses less memory than a listener per item. Every addEventListener should have a matching removeEventListener with the same function reference and options, or the listener keeps its closure and the node alive.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
For a click on a nested button inside a div with a listener on both, in what order do bubbling listeners run?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptdiv.addEventListener('click', () => log('div')); button.addEventListener('click', () => log('button'));Exercise 2Explain
Explain event delegation and why it is useful for a list that grows.
starter.textlist.addEventListener('click', (e) => { if (e.target.matches('li')) select(e.target); });Reveal the reference answer
reference.textDelegation attaches one listener to a common ancestor and uses event.target to find which child was clicked. Because the event bubbles, items added after the listener is registered are covered without new listeners. It uses less memory than one listener per item and survives re-rendering, since the container stays in place.Authored expected output: one listener handles all items
The answer should name the ancestor listener, event.target and bubbling, and connect them to dynamically added items and memory.
Exercise 3Implement
Implement `delegate(root, selector, type, handler)` so it calls handler when an event of type bubbles from an element matching selector.
starter.javascriptfunction delegate(root, selector, type, handler) { // your code here }Reveal the reference answer
reference.javascriptfunction delegate(root, selector, type, handler) { const listener = (event) => { const target = event.target.closest(selector); if (target && root.contains(target)) handler.call(target, event); }; root.addEventListener(type, listener); return () => root.removeEventListener(type, listener); }Authored expected output: handler runs with the matching element as this
closest walks up from the event target to find a match, and contains guards against matches outside the root. Returning a cleanup function makes removal easy.
Exercise 4Debug
This comment renderer is vulnerable to injected markup. Find and fix the bug.
starter.javascriptfunction renderComment(comment) { const el = document.createElement('p'); el.innerHTML = comment.text; return el; }Reveal the reference answer
reference.javascriptfunction renderComment(comment) { const el = document.createElement('p'); el.textContent = comment.text; return el; }Authored expected output: the comment text is inserted as plain text
innerHTML parses the string as markup, so a comment containing a script or an event attribute can execute. textContent inserts the value as text, which neutralizes the injection.
Exercise 5Test
Write assertions that prove preventDefault cancels the default action while stopPropagation stops bubbling.
starter.javascriptfunction assertEqual(actual, expected, label) { if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(label + ': unexpected value'); }Reveal the reference answer
reference.javascriptconst order = []; const parent = document.createElement('div'); const child = document.createElement('span'); parent.append(child); child.addEventListener('click', (e) => { order.push('child'); e.stopPropagation(); }); parent.addEventListener('click', () => order.push('parent')); child.dispatchEvent(new Event('click', { bubbles: true })); assertEqual(order, ['child'], 'stopPropagation prevents the parent listener'); console.log('all assertions passed');Authored expected output: all assertions passed
stopPropagation ends the event's trip up the tree, so the parent listener never runs. preventDefault would only cancel the browser default, not the propagation.
Exercise 6Interview
How do you avoid memory leaks from DOM event listeners in a long-lived page?
Reveal the reference answer
reference.textI pair every addEventListener with a removeEventListener using the same function reference and options, and I do it in the component's cleanup. I prefer delegation so one listener covers many nodes, and I use AbortController's signal to remove a group of listeners at once. I avoid anonymous inline handlers when I need to remove them, because I cannot reference them again.The answer should name symmetric registration and removal, delegation, AbortController and the anonymous-handler problem.
Common misconceptions
#- innerHTML is safe because the string comes from the same page.
- preventDefault stops the event from reaching parent elements.
- A listener is removed automatically when its element is gone.
Follow-up practice
#- javascript-foundations-debounce-and-throttle
- javascript-foundations-browser-storage
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.