Courses / Frontend System Design, with JavaScript Foundations / Chapter 6
Module 3 · Browser Foundations · Chapter 6 of 21
The DOM, Events and Observers
Builds on this, Prototypes and Classes and Promises, Async Code and the Browser Event Loop. Next up: How the Browser Loads and Renders a Page.
Part 1 · The DOM tree
Nodes and collections
Every framework ends up calling the same browser APIs to build elements and react to input. Each behaviour below was measured in Chrome 157.
The Document Object Model (DOM) is the browser's live, in-memory tree of the page. Each tag, piece of text and comment becomes a node, and nodes that come from tags are elements. Scripts read and change that tree, and the browser redraws the page to match.
Every example in this chapter runs in a real Chrome page driven by Playwright. A small helper opens Chrome, loads some HTML, hands the page to your code and prints whatever the page logs.
import { chromium } from 'playwright-core' export async function withPage(html, steps, args = []) { const browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', args, }) const page = await browser.newPage() page.on('console', (m) => console.log(m.text())) await page.setContent(html) await steps(page) await browser.close() }
harness.mjs, shared by every example in this chapter.
Two kinds of collection come back from DOM queries, and they behave differently. querySelectorAll returns a static NodeList: a snapshot taken at the moment of the call. Properties such as children and methods such as getElementsByTagName return a live HTMLCollection, which always reflects the current tree. The example below adds a third item after taking both.
import { withPage } from './harness.mjs' await withPage('<ul id="cart"><li>Pen</li><li>Ink</li></ul>', (page) => page.evaluate(() => { const ul = document.querySelector('#cart') const snapshot = ul.querySelectorAll('li') const live = ul.children const tape = document.createElement('li') tape.textContent = 'Tape' ul.append(tape) console.log('static', snapshot.length, 'live', live.length) console.log(snapshot.constructor.name, live.constructor.name) console.log(typeof snapshot.forEach, typeof live.forEach) console.log(ul.childNodes.constructor.name, ul.childNodes.length) }))
static 2 live 3 NodeList HTMLCollection function undefined NodeList 3
Output (Chrome 157)
The snapshot still holds 2 items and the live collection holds 3. The last two lines show that the split is not simply "NodeList is static": childNodes is a NodeList and it is live. The safe habit is to ask which kind you hold before looping and changing the tree at the same time, because a loop over a live collection can skip items or never end when each pass adds one. An HTMLCollection also has no forEach, so copy it with Array.from or the spread operator when you need array methods.
Building nodes in memory
document.createElement makes an element that belongs to no tree yet, and append attaches it. Every attachment to the live document can cost the browser some style and layout work later, so code that adds many nodes should assemble them first and attach them once. The tool for that is a DocumentFragment, a lightweight container that is not part of the page.
import { withPage } from './harness.mjs' await withPage('<ul id="cart"></ul>', (page) => page.evaluate(() => { const ul = document.querySelector('#cart') const frag = new DocumentFragment() for (const name of ['Pen', 'Ink', 'Tape']) { const li = document.createElement('li') li.textContent = name frag.append(li) } console.log('fragment before', frag.children.length) ul.append(frag) console.log('fragment after', frag.children.length) console.log('list', ul.children.length, ul.textContent) }))
fragment before 3 fragment after 0 list 3 PenInkTape
Output (Chrome 157)
Appending the fragment moves its children into the list in one operation and leaves the fragment empty, as the second line shows. The fragment never appears in the tree itself. Appending nodes one at a time and appending a fragment give the same result, so the difference is in how many separate changes the browser has to process. The rendering chapter measures that cost.
Text versus markup
Two properties set the content of an element, and they mean different things. textContent stores a string as text: any angle brackets in it are plain characters. innerHTML parses the string as HTML and builds nodes from it.
import { withPage } from './harness.mjs' await withPage('<body></body>', (page) => page.evaluate(() => { const input = '<b onclick="steal()">bold</b>' const a = document.createElement('p') a.textContent = input console.log(a.children.length, a.textContent) const b = document.createElement('p') b.innerHTML = input console.log(b.children.length, b.firstChild.tagName) console.log(b.firstChild.getAttribute('onclick')) }))
0 <b onclick="steal()">bold</b> 1 B steal()
Output (Chrome 157)
With textContent the element has no child elements and shows the characters exactly as given. With innerHTML the element gets a real <b> child, and the onclick attribute survived the parse, so the handler code would run on a click. If the string came from a user, that is a script injection. Use textContent for anything that is not markup you wrote yourself, and build structure with createElement. The security chapter covers sanitising for the cases where you must accept HTML.
A ul has two li children. You take ul.querySelectorAll('li') and ul.children, then append a third li. What are the two lengths?
- The
NodeListfromquerySelectorAllstays at 2 because it is a snapshot. - The
HTMLCollectioninchildrenreports 3 because it is live.
What happens to a DocumentFragment after you append it to an element?
- Its children move into the element, so the fragment is empty afterwards.
- The fragment itself never becomes part of the page.
Why use textContent rather than innerHTML for text that came from a user?
textContentkeeps characters as text, so no elements or event attributes are created.
Part 2 · How events travel
Three phases
A click on a button is also a click on the cell that holds it, the row, the table and the page. The browser does not guess which of them cares. It runs a fixed procedure called event dispatch, defined in the DOM standard, that visits each ancestor in a set order.
Dispatch has three phases. In the capture phase the event travels from the window down through each ancestor to the parent of the target, the element the event happened on. In the target phase it runs the target's own listeners. In the bubble phase it travels back up the same path. A listener says which of the two outer phases it wants through its capture option, and the default is the bubble phase.
The example registers a listener for both phases on five nodes and logs the order after one real click on the button. The HTML parser added a tbody between the table and the row, but it has no listeners here.
import { withPage } from './harness.mjs' const html = `<table id="t"><tr id="row"><td> <button id="b">Buy</button></td></tr></table>` await withPage(html, async (page) => { await page.evaluate(() => { const names = { 1: 'capture', 2: 'target', 3: 'bubble' } const nodes = { window, document, table: t, row, button: b, } for (const [label, node] of Object.entries(nodes)) { for (const capture of [true, false]) { node.addEventListener('click', (e) => { console.log(names[e.eventPhase].padEnd(8), label.padEnd(8), e.target === node ? 'target' : '') }, capture) } } }) await page.click('#b') })
capture window capture document capture table capture row target button target target button target bubble row bubble table bubble document bubble window
Output (Chrome 157)
The log reads down the page and back up. The button appears twice because it has one capture listener and one bubble listener, both run in the target phase. Most listeners are bubble listeners, which is why you normally see an inner element's handler run before an outer one.
target and currentTarget
Two properties of the event object are easy to confuse. event.target is the element where the event started. event.currentTarget is the element whose listener is running right now. Inside a plain function listener, this is the same as currentTarget, as the classes chapter showed.
import { withPage } from './harness.mjs' const html = `<div id="outer"><span id="inner">hi</span></div>` await withPage(html, async (page) => { await page.evaluate(() => { outer.addEventListener('click', function (e) { console.log('target:', e.target.id) console.log('currentTarget:', e.currentTarget.id) console.log('this === currentTarget:', this === e.currentTarget) }) }) await page.click('#inner') await page.evaluate(() => outer.click()) })
target: inner currentTarget: outer this === currentTarget: true target: outer currentTarget: outer this === currentTarget: true
Output (Chrome 157)
The first click lands on the inner span, so target is inner while the listener on outer sees itself as currentTarget. The second click comes from outer.click(), a script call, where both are outer. Code that reads event.target to decide what was clicked is therefore reading the innermost element, not the one it attached the listener to. An arrow function has no this of its own, so inside an arrow listener use event.currentTarget instead.
Stopping and cancelling
Two methods change how far an event travels. stopPropagation() stops it moving to the next node, but the other listeners on the current node still run. stopImmediatePropagation() also stops the remaining listeners on the current node.
import { withPage } from './harness.mjs' const html = `<div id="outer"> <button id="one">one</button><button id="two">two</button></div>` await withPage(html, async (page) => { await page.evaluate(() => { const log = (m) => console.log(m) outer.addEventListener('click', (e) => { log(' outer ' + e.target.id) }) for (const [btn, stop] of [[one, 'stopPropagation'], [two, 'stopImmediatePropagation']]) { btn.addEventListener('click', () => log(` ${btn.id} first`)) btn.addEventListener('click', (e) => e[stop]()) btn.addEventListener('click', () => log(` ${btn.id} third`)) } }) for (const id of ['one', 'two']) { console.log('click', id) await page.click('#' + id) } })
click one one first one third click two two first
Output (Chrome 157)
Button one stops propagation in its second listener, so its third listener still runs but outer never hears about the click. Button two stops immediately, so even its third listener is skipped. Stopping propagation breaks any ancestor that relies on bubbling, such as a delegated handler or an analytics hook, so it is better left alone unless you own both ends.
preventDefault() is a different thing: it cancels the browser's own action for the event, such as following a link, and it does not stop the event travelling. The link below goes nowhere when a listener prevents the default.
import { withPage } from './harness.mjs' const html = `<a id="plain" href="#plain">plain</a> <a id="held" href="#held">held</a>` await withPage(html, async (page) => { await page.evaluate(() => { held.addEventListener('click', (e) => { e.preventDefault() console.log('defaultPrevented', e.defaultPrevented) }) }) for (const id of ['plain', 'held']) { await page.click('#' + id) console.log(id, '-> hash', JSON.stringify( await page.evaluate(() => location.hash))) } })
plain -> hash "#plain" defaultPrevented true held -> hash "#plain"
Output (Chrome 157)
Clicking plain changes the hash to #plain. Clicking held leaves the hash at #plain because the default navigation was cancelled. Only events that are cancelable can be prevented, and a listener marked passive cannot prevent anything, which lesson 4 shows.
Part 3 · Event delegation
One listener instead of many
Event delegation means putting one listener on a common ancestor and working out from event.target which child was meant. It works because of the bubble phase from the last lesson: a click on any row reaches the table.
A table with 2,000 rows shows the difference. The first approach attaches a listener to every row. The second attaches one to the table and calls closest to find the row. The page holds the 2,000 rows in a table with the id t. The script counts calls to addEventListener, then clicks a row, then inserts a row after both listeners were attached and clicks that too.
console.log(await page.evaluate((late) => { let calls = 0 const add = EventTarget.prototype.addEventListener EventTarget.prototype.addEventListener = function (...a) { calls++ return add.apply(this, a) } window.hits = [] for (const tr of t.querySelectorAll('tr')) { tr.addEventListener('click', () => { hits.push('own ' + tr.dataset.id) }) } const own = calls calls = 0 t.addEventListener('click', (e) => { const row = e.target.closest('tr') if (row) hits.push('delegated ' + row.dataset.id) }) t.insertAdjacentHTML('beforeend', late) return `listeners: per row ${own}, delegated ${calls}` }, late))
listeners: per row 2000, delegated 1 [ 'own 7', 'delegated 7', 'delegated 2001' ]
Output (Chrome 157)
The per-row approach made 2,000 registrations and the delegated one made 1. The clicks show the second difference. The existing row 7 triggered both listeners. The new row 2001 triggered only the delegated one, because nobody attached a listener to it. With delegation, rows that a framework adds, removes or replaces keep working with no extra code, and there is nothing to clean up per row.
Finding the row with closest
The click target is usually the innermost element, here the span inside a cell, not the row you want. element.closest(selector) starts at the element itself and walks up through its ancestors, returning the first that matches the selector, or null if none does. It checks the element itself first, so a click directly on the row also works.
Watch for closest('tr') testing each ancestor until one matches
Read it as steps
closest tests the element, then each ancestor, and stops at the first match.
The delegated handler in the last example does exactly this: it calls e.target.closest('tr'), and if the result is null, the click was somewhere else in the table and the handler ignores it. Always test the result, because clicks on padding or on a header row also bubble to the table.
Two cautions apply. First, closest can match an element outside the one you delegated on if the selector is loose, so check that the match is inside the container with container.contains(match) when the container is nested in other matching elements. Second, a delegated listener sees the event only after it bubbles, so any code that stops propagation below it hides the event.
A reusable delegate helper
Delegation code repeats the same three steps: find the match, check it is inside the container, call the handler. A small helper holds them once. The version below also guards the first step, because event.target is not always an element.
await withPage(html, async (page) => { await page.evaluate(() => { function delegate(root, type, selector, handler, options) { root.addEventListener(type, (e) => { const t = e.target const hit = t instanceof Element && t.closest(selector) if (hit && root.contains(hit)) handler(e, hit) }, options) } list.addEventListener('click', (e) => { const card = e.target.closest('.card') console.log('bare closest(.card) found:', !!card) }) delegate(list, 'click', '.card', () => console.log('helper .card')) delegate(list, 'click', 'li', (e, li) => { console.log('helper li:', li.textContent) }) }) await page.click('li') })
bare closest(.card) found: true helper li: One
Output (Chrome 157)
The page has a .card that wraps the list. A bare closest('.card') inside the list handler finds that card even though it sits outside the list, which is the loose-selector problem from the previous page. The helper rejects it, because root.contains(hit) is false, and handles only the li. The helper passes options through, so it accepts signal and every other option from the next lesson. Frameworks ship their own version of this idea, so you will often meet it as a built-in rather than written by hand.
Events that do not bubble
Not every event bubbles. focus and blur do not, and neither do mouseenter and mouseleave. A delegated listener for them on an ancestor never fires in the bubble phase. There are two ways around that. Listen in the capture phase, which every event goes through, or use the bubbling twins focusin and focusout.
import { withPage } from './harness.mjs' const html = '<form id="f"><input id="name"></form>' await withPage(html, async (page) => { await page.evaluate(() => { const log = (m) => console.log(m) f.addEventListener('focus', () => log('form: focus, bubbling')) f.addEventListener('focus', () => log('form: focus, capture'), true) f.addEventListener('focusin', () => log('form: focusin')) }) await page.focus('#name') })
form: focus, capture form: focusin
Output (Chrome 157)
Focusing the input produced the capture listener and focusin, and skipped the bubble listener for focus. For hover effects on many items, prefer mouseover and mouseout, which bubble, or CSS :hover, which needs no script at all.
Why does a delegated listener keep working for rows added after the page loaded?
- It sits on the ancestor, and any new row's events bubble up to it, so the new row needs no listener of its own.
What does closest('tr') return when called on an element that is itself a tr?
- The element itself, because
closesttests the starting element before its ancestors.
Which listener options let an ancestor see a focus event on a child?
- Register in the capture phase with
{ capture: true }or listen forfocusin, becausefocusdoes not bubble.
Part 4 · Listener options
The options object
addEventListener takes a third argument that is either a boolean for capture or an options object. The options are capture, once, passive and signal. The previous lessons used capture. This lesson covers the other three, which change how a listener lives or behaves.
once: true removes the listener automatically after it runs the first time. It suits one-off work such as an intro animation end or a first-interaction hook.
import { withPage } from './harness.mjs' await withPage('<button id="b">go</button>', async (page) => { await page.evaluate(() => { const log = (m) => console.log(m) b.addEventListener('click', () => log('once: runs'), { once: true }) b.addEventListener('click', () => log('plain: runs')) }) for (let i = 1; i <= 2; i++) { console.log('click', i) await page.click('#b') } })
click 1 once: runs plain: runs click 2 plain: runs
Output (Chrome 157)
The once listener ran on the first click only. The plain listener ran both times. The browser removes a once listener before calling it, so it does not run again even if it throws.
Passive listeners
Scrolling must stay smooth, but a wheel or touchstart listener could call preventDefault() and cancel the scroll. Without a promise that it will not, the browser has to wait for each listener to finish before it can scroll. A passive listener is that promise: { passive: true } tells the browser the listener will never call preventDefault, so scrolling can proceed at once. If the listener calls it anyway, the call is ignored.
Browsers apply that promise for you in some places. Per MDN, passive defaults to true for wheel, mousewheel, touchstart and touchmove listeners on window, document, document.documentElement and document.body, and to false everywhere else. The script checks four cases by dispatching an event and seeing whether preventDefault took effect.
import { withPage } from './harness.mjs' await withPage('<div id="box">box</div>', async (page) => { const rows = await page.evaluate(() => { const check = (label, target, type, opts) => { let ignored = false target.addEventListener(type, (e) => { e.preventDefault() ignored = !e.defaultPrevented }, opts) target.dispatchEvent(new Event(type, { cancelable: true })) return label.padEnd(28) + (ignored ? 'ignored' : 'honoured') } return [ check('window wheel', window, 'wheel'), check('window wheel, passive false', window, 'wheel', { passive: false }), check('box wheel', box, 'wheel'), check('window click', window, 'click'), ] }) console.log(rows.join('\n')) })
window wheel ignored window wheel, passive false honoured box wheel honoured window click honoured
Output (Chrome 157)
The wheel listener on window had its preventDefault ignored until { passive: false } was set. The same event type on a div and a click on window were honoured, which matches the MDN rule. A real mouse wheel shows the browser warning.
import { withPage } from './harness.mjs' const html = '<div style="height:3000px">tall</div>' await withPage(html, async (page) => { await page.evaluate(() => { window.addEventListener('wheel', (e) => { e.preventDefault() console.log('handler ran, defaultPrevented:', e.defaultPrevented) }) }) await page.mouse.move(100, 100) await page.mouse.wheel(0, 300) await page.waitForTimeout(500) console.log('scrollY', await page.evaluate(() => Math.round(scrollY))) })
Matching on removal
A listener is identified by three things: the event type, the function and the capture flag. removeEventListener must be given the same three to find it. The other options, once, passive and signal, are not part of the match. Forgetting the capture flag is a classic reason a listener seems impossible to remove.
import { withPage } from './harness.mjs' await withPage('<button id="b">go</button>', async (page) => { await page.evaluate(() => { window.handler = () => console.log('handler ran') b.addEventListener('click', handler, true) b.removeEventListener('click', handler) }) console.log('after removeEventListener without capture:') await page.click('#b') await page.evaluate(() => { b.removeEventListener('click', handler, true) }) console.log('after removeEventListener with capture:') await page.click('#b') console.log('(nothing ran)') })
after removeEventListener without capture: handler ran after removeEventListener with capture: (nothing ran)
Output (Chrome 157)
The first removal named the function but not capture, so it matched nothing and the handler still ran. The second named it correctly and the handler was gone. The signal option, covered next, avoids the problem, because a signal needs no function or flag to remove a listener.
| Option | Default | Use it to |
|---|---|---|
capture | false | see an event before the target does |
once | false | run a listener one time then remove it |
passive | false, except wheel and touch events on window, document, html and body | promise not to cancel, so scrolling stays smooth |
signal | none | remove one or many listeners with a single abort call |
Removing many listeners with signal
removeEventListener needs the same function and the same capture value you registered, which is awkward for arrow functions and for components that register many listeners. The signal option replaces that bookkeeping. Pass an AbortSignal from an AbortController and calling abort() removes every listener that was registered with it.
import { withPage } from './harness.mjs' await withPage('<button id="b">go</button>', async (page) => { await page.evaluate(() => { const ctrl = new AbortController() window.ctrl = ctrl let n = 0 for (const type of ['click', 'keydown', 'pointerdown']) { b.addEventListener(type, () => console.log(++n, type), { signal: ctrl.signal }) } }) console.log('before abort') await page.click('#b') await page.evaluate(() => ctrl.abort()) console.log('after abort') await page.click('#b') console.log('done, no output after abort') })
before abort 1 pointerdown 2 click after abort done, no output after abort
Output (Chrome 157)
Three listeners on one button share a signal. The click fired pointerdown and click listeners, then abort() removed all three at once, and the second click printed nothing. A component can create one controller when it mounts and abort it when it unmounts, whatever number of listeners it added, including ones on window and document. The event loop chapter showed the same AbortSignal cancelling a request, and one controller can do both jobs.
What does { once: true } do?
- It removes the listener automatically right before it runs the first time, so it runs at most once.
Why did the wheel listener on window ignore preventDefault?
- Browsers treat
wheellisteners onwindow,documentandbodyas passive by default. { passive: false }turns that off for a listener that really needs to cancel scrolling.
How does one AbortController clean up listeners on several targets?
Part 5 · Observers and leaks
MutationObserver
Polling the DOM to find out whether something changed wastes work. The platform provides observers that tell you instead. A MutationObserver reports changes to the tree: children added or removed, attributes changed, text edited.
Its callback does not run at the moment of each change. The browser records changes and delivers them together, as a microtask, after the current script finishes, as the event loop chapter showed.
import { withPage } from './harness.mjs' await withPage('<div id="box"></div>', (page) => page.evaluate(async () => { const mo = new MutationObserver((records) => console.log('observer callback, records:', records.length)) mo.observe(box, { childList: true }) setTimeout(() => console.log('timeout'), 0) box.append(document.createElement('i')) box.append(document.createElement('i')) Promise.resolve().then(() => console.log('promise')) console.log('after two appends, still synchronous') await new Promise((r) => setTimeout(r, 50)) mo.disconnect() }))
after two appends, still synchronous
observer callback, records: 2
promise
timeoutOutput (Chrome 157)
Two appends happened synchronously and the line after them printed first. Then the observer callback ran once with both records, ahead of the timer. The batching is why a single observer callback can handle a burst of changes, and the microtask timing means you see the final state, not each step. A callback that itself changes the observed tree creates more records and runs again, so guard against loops.
IntersectionObserver and ResizeObserver
An IntersectionObserver reports when an element enters or leaves the viewport, or another container, and by how much it overlaps. It replaces scroll listeners that measured positions on every scroll event, which forces layout. The classic uses are lazy loading, infinite scroll and impression counting.
A ResizeObserver reports when an element's box changes size, which a resize listener on window cannot do because it sees only the viewport. Container-aware components rely on it. In the example the page has a 200 pixel wide card between two tall spacers, and both observers watch the card.
await withPage(html, async (page) => { await page.evaluate(() => { new IntersectionObserver((entries) => { for (const e of entries) { console.log('intersection:', e.isIntersecting, 'ratio', e.intersectionRatio.toFixed(1)) } }, { rootMargin: '0px' }).observe(card) new ResizeObserver((entries) => { for (const e of entries) { console.log('resize:', Math.round(e.contentRect.width), 'wide') } }).observe(card) }) await page.waitForTimeout(200) console.log('-- scroll to card') await page.evaluate(() => card.scrollIntoView()) await page.waitForTimeout(200) console.log('-- widen card') await page.evaluate(() => { card.style.width = '320px' }) await page.waitForTimeout(200) })
resize: 200 wide intersection: false ratio 0.0 -- scroll to card intersection: true ratio 1.0 -- widen card resize: 320 wide
Output (Chrome 157)
Both observers called back as soon as they started watching, before anything changed: the resize entry reported the initial 200 pixel width, and the intersection entry reported that the card was off screen. Code that reacts to these callbacks should expect a first call that describes the starting state. After the scroll the card was fully visible, with a ratio of 1.0, and after it was widened the resize observer reported 320 pixels.
Detached nodes and listeners that outlive them
JavaScript frees an object when nothing can reach it. A DOM node you remove from the page is detached, and it can still be reached by any variable, closure or listener that refers to it. A listener on a long-lived target, such as window, that closes over an element keeps that element and its whole subtree alive. This is a common DOM memory leak in single page apps: a component adds a resize listener to window on mount, never removes it, and every instance that was ever mounted stays in memory.
You can test this without a profiler. A WeakRef holds an object without keeping it alive, and Chrome started with --js-flags=--expose-gc offers a gc() function. The script makes three elements, removes them all from the page, collects garbage and asks each weak reference whether its element survived.
await withPage('<div id="host"></div>', async (page) => { await page.evaluate(() => { window.refs = {} const make = (name, onWindow) => { const el = document.createElement('div') const ctrl = new AbortController() host.append(el) if (onWindow) { window.addEventListener('resize', () => el.id, { signal: ctrl.signal }) } window.refs[name] = new WeakRef(el) return ctrl } make('no listener', false) make('window listener', true) make('listener with signal', true).abort() host.replaceChildren() })
const names = ['no listener', 'window listener', 'listener with signal'] for (const name of names) { const alive = await page.evaluate(async (n) => { for (let i = 0; i < 5; i++) { await new Promise((r) => setTimeout(r, 50)) gc() } return refs[n].deref() !== undefined }, name) console.log(name.padEnd(22), 'alive after gc:', alive) } }, flags)
The checking half of the same file.
no listener alive after gc: false window listener alive after gc: true listener with signal alive after gc: false
Output (Chrome 157)
The element with no listener was collected. The element held by the window listener survived, even though it is no longer on the page. The third element had the same listener registered with a signal, aborted before removal, and was collected. The fix for a component is the pattern from the previous lesson: one AbortController per mount and one abort() per unmount. Observers need the same care, since an observer holds its targets until you call disconnect() or unobserve().