DOM & Events

The Document Object Model — querying and manipulating nodes, the event model (capture, target, bubble), event delegation, preventDefault vs stopPropagation, common Web APIs (fetch, storage, observers), and performance considerations.

Beginner 3 min readLesson 5 of 14

The DOM (Document Object Model) is the browser's live, tree-shaped representation of the page. JavaScript reads and changes it; the browser re-renders accordingly. It's an API, not part of JavaScript itself — the same API exists in other languages (e.g. jsdom in Node).

The tree

titleheadh1liliulbodyhtmldocument

Every node is an object: element nodes (<ul>), text nodes, comments, and the document itself. Elements have properties (id, className, value), attributes, children and a parent.

Selecting elements

JavaScript
const btn   = document.getElementById("save");
const first = document.querySelector(".card");           // first match (CSS selector)
const all   = document.querySelectorAll(".card");        // static NodeList
const link  = btn.closest("form");                       // nearest ancestor matching
const items = list.children;                             // live HTMLCollection of elements

for (const card of document.querySelectorAll(".card")) { /* NodeList is iterable */ }

Changing the DOM

JavaScript
// Content
el.textContent = userInput;            // safe: treated as text
el.innerHTML = "<b>Hi</b>";            // parses HTML — never with untrusted input (XSS)

// Attributes, classes, styles, data
el.setAttribute("aria-expanded", "true");
el.classList.add("active");  el.classList.toggle("open");
el.style.setProperty("--progress", "40%");
el.dataset.userId;                     // reads data-user-id="…"

// Creating and inserting
const li = document.createElement("li");
li.textContent = "New item";
list.append(li);                       // also prepend, before, after, replaceWith
li.remove();

// Many nodes: build off-DOM, insert once
const frag = document.createDocumentFragment();
for (const name of names) {
  const li = document.createElement("li");
  li.textContent = name;
  frag.append(li);
}
list.append(frag);                     // one insertion → one layout

Events

JavaScript
button.addEventListener("click", (event) => {
  console.log(event.type, event.target, event.currentTarget);
});

input.addEventListener("input", e => search(e.target.value));
form.addEventListener("submit", e => {
  e.preventDefault();                       // stop the browser's default full-page submit
  save(new FormData(form));
});

window.addEventListener("scroll", onScroll, { passive: true });   // promise not to preventDefault
el.addEventListener("click", handler, { once: true });            // auto-remove after one call

const ctrl = new AbortController();
el.addEventListener("pointermove", onMove, { signal: ctrl.signal });
ctrl.abort();                                                      // removes the listener

Propagation: capture, target, bubble

When you click a <button> inside a <li> inside a <ul>, the event travels in three phases:

  1. Capture: from window down through ancestors to the target (listeners with { capture: true }).
  2. Target: listeners on the clicked element itself.
  3. Bubble: back up through every ancestor to window (the default phase for listeners).
  • event.target — the element where the event originated (the button).
  • event.currentTarget — the element whose listener is running now.
  • event.stopPropagation() — stop travelling to further ancestors (rarely needed; it breaks analytics and outer handlers).
  • event.preventDefault() — cancel the browser's default action (following a link, submitting a form, checking a box). It doesn't stop propagation.

Not all events bubble (focus, blur, mouseenter don't; use focusin/focusout).

Event delegation

Instead of a listener on each of 1,000 rows, put one listener on the container and use target to find which row was clicked. It uses less memory and automatically works for rows added later:

JavaScript
document.querySelector("#todo-list").addEventListener("click", (e) => {
  const button = e.target.closest("button[data-action]");
  if (!button) return;
  const id = button.closest("li").dataset.id;
  if (button.dataset.action === "delete") deleteTodo(id);
  if (button.dataset.action === "toggle") toggleTodo(id);
});

React and most frameworks use delegation internally (React attaches listeners at the root).

Common event types

CategoryEvents
Pointer / mouseclick, dblclick, pointerdown, pointermove, pointerup, contextmenu
Keyboardkeydown, keyup (e.key, e.code, modifier flags)
Forminput, change, submit, focus, blur, invalid
DocumentDOMContentLoaded (DOM ready), load (all resources), visibilitychange
Windowresize, scroll, popstate, online, offline

Use pointer events for unified mouse, touch and pen input. Throttle or debounce noisy events like scroll, resize and input.

JavaScript
function debounce(fn, ms) {
  let t;
  return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
search.addEventListener("input", debounce(e => fetchResults(e.target.value), 250));

Useful Web APIs

APIFor
fetchHTTP requests (returns Promises — Promises)
localStorage / sessionStorageSmall synchronous key–value storage (strings; ~5 MB)
IndexedDBLarge structured client-side storage
IntersectionObserverDetect when elements enter the viewport (lazy loading, infinite scroll)
ResizeObserver / MutationObserverReact to element size changes / DOM changes
history.pushState, popstateClient-side routing
requestAnimationFrameRun visual updates before the next frame
Web WorkersRun JS off the main thread
navigator.clipboard, Geolocation, NotificationsDevice features (permission-gated)
JavaScript
const io = new IntersectionObserver((entries) => {
  for (const e of entries) {
    if (e.isIntersecting) { e.target.src = e.target.dataset.src; io.unobserve(e.target); }
  }
}, { rootMargin: "200px" });
document.querySelectorAll("img[data-src]").forEach(img => io.observe(img));

Why frameworks exist

Manually keeping the DOM in sync with changing data — adding, removing and updating the right nodes as state changes — gets error-prone fast. Frameworks like React let you describe the UI as a function of state and compute the DOM updates for you (React fundamentals).

Key takeaways
  • The DOM is a live tree of node objects; query with querySelector/All and closest.
  • Use textContent and createElement for content; innerHTML with untrusted data causes XSS.
  • Batch insertions with DocumentFragment to minimise layouts.
  • Events capture down, hit the target, then bubble up; preventDefault cancels default actions, stopPropagation stops travel.
  • Event delegation: one listener on a container handles many (and future) children.
  • Observers, fetch, storage and workers are the core Web APIs.