DOM & the event model

Capture/bubble phases, delegation, custom events, DOM measurement APIs. Delegation on a 1,000-item list is a classic machine-coding checkpoint.

About 27 min read3-question knowledge check

The mental model

The DOM is a live tree that mirrors the document, and events are messages that travel through that tree — down from the root to a target, then back up. Almost every DOM bug is one of two things: touching the tree in a way that forces the browser to redo geometry work it had batched, or misunderstanding which direction an event is travelling when your handler runs.

The analogy that sticks: a corporate mailroom. An event is a memo addressed to one desk (the target). It does not teleport there — it comes in through reception (the document root), is carried down through every department on the way (the capture phase), reaches the desk (the target phase), then is carried back up the same path so every manager en route can also see it (the bubble phase). Event delegation is the manager who says "don't give every clerk their own inbox — route it all through me and I'll dispatch by who it was addressed to." That one decision is why a 10,000-row table can have a single click handler instead of 10,000.

What breaks without this model is concrete. Attaching a listener to every item in a long list is a memory and setup cost that shows up as slow renders and leaks. Reading offsetHeight in a loop that also writes styles forces the browser to recompute layout on every iteration — a 300-element loop becomes visible jank. A handler that assumes it runs at the target, when it actually runs during bubbling from a child, fires for the wrong element. And a listener on a long-lived object such as window or document that is never removed keeps its closure, and any node that closure references, alive. None of these are browser quirks; they are the tree and the event model behaving exactly as specified while you expected something else.

The second half of the mental model: the DOM is the slow boundary. JavaScript is fast; the DOM is a separate system your JS talks to across a bridge, and each crossing that reads geometry can force the browser to flush pending work. Fast DOM code is code that crosses that bridge in batches — all reads, then all writes — and never in an alternating read/write loop.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision