Skip to content
LumenaryAcademy
Professional 60 min

In the browser: the DOM and events

How JavaScript reads and changes a web page, responds to the people using it, and does so safely and quickly.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

What the browser adds

Everything so far has been the language itself, run by Node. In a browser the language is identical, but the host provides a different world: a document to read and change, events from the people using the page (clicks, key presses, touches, form submissions), the network through fetch, storage, graphics, audio and more. This combination is what made JavaScript the language of the web, and it is where most JavaScript in the world still runs.

This lesson describes that world. Browser code cannot be run by this course's test suite, which uses Node, so code that needs a page is shown in plain blocks with an explanation; copy it into a page of your own, or into the console of your browser's developer tools, to try it. Where the browser's behaviour can be shown faithfully without a page (the event API itself, which Node also implements, and the rules by which events travel through a page), the lesson uses real, tested programs.

IntuitionH

The DOM: a page as a tree of objects

Definition— DOM

The Document Object Model is the browser's representation of a page as a tree of objects called nodes. Each HTML element becomes an element node, the text inside it becomes text nodes, and the whole tree hangs from the document object. JavaScript reads and changes the page by reading and changing this tree; the browser then updates what is on the screen.

This HTML:

html
<body>
  <h1>Market prices</h1>
  <ul id="prices">
    <li data-item="maize">Maize: <span class="price">320</span></li>
    <li data-item="beans">Beans: <span class="price">910</span></li>
  </ul>
  <button id="refresh" type="button">Refresh</button>
</body>

becomes a tree like this:

documentbodyh1ul#pricesbutton#refreshli (maize)li (beans)spanspan
The DOM tree for the market-prices page (text nodes omitted). Events travel down this tree and back up it.

The everyday operations, all in browser code:

javascript
// Find elements with CSS selectors.
const list = document.querySelector("#prices");              // first match, or null
const prices = document.querySelectorAll("#prices .price");   // all matches (a NodeList)

// Read and change text, attributes, classes and styles.
for (const span of prices) {
  span.textContent = String(Number(span.textContent) * 1.1); // update the text
}
list.querySelector("li").classList.add("highlight");         // add a CSS class
const item = list.lastElementChild.dataset.item;             // reads data-item: "beans"

// Create, insert and remove elements.
const li = document.createElement("li");
li.dataset.item = "sorghum";
li.textContent = "Sorghum: 450";
list.append(li);                                             // add as the last child
list.firstElementChild.remove();                             // remove maize

querySelector and querySelectorAll accept any CSS selector, so the same language you use to style elements also finds them. textContent gets or sets the plain text of an element; classList adds, removes and toggles CSS classes, which is the clean way to change appearance (leave the actual styles to the stylesheet); dataset reads data-* attributes, the standard place to attach your own data to an element. append, prepend, before, after, replaceWith and remove cover nearly all changes to the tree.

Your script must run after the elements it looks for exist. <script type="module" src="app.js"> in the page's head waits until the HTML has been parsed, and so does a classic script with the defer attribute; either is the modern answer to the old advice "put scripts at the end of the body".

DefinitionsH

Events and how they travel

Definition— event listener

An event is an object describing something that happened: a click, a key press, a form being submitted, a resource finishing loading. target.addEventListener(type, listener, options) registers a function to be called with that object whenever an event of that type reaches the target. Event listeners are callbacks, and they run as tasks of the event loop from the previous lesson.

The listener API is defined by the DOM standard on a class called EventTarget, and Node implements the same class, so you can explore the API itself without a page:

javascript
// EventTarget and Event are web standards, and Node implements them too,
// so the listener API you use on buttons can be explored right here.
const door = new EventTarget();
const knock = (visitor) => {
  console.log(`-- ${visitor} knocks`);
  door.dispatchEvent(new CustomEvent("knock", { detail: { visitor } }));
};

function greet(event) {
  console.log(`greet: a ${event.type} from ${event.detail.visitor}`);
}
door.addEventListener("knock", greet);
door.addEventListener("knock", () => console.log("bark"));
door.addEventListener("knock", () => console.log("first-visitor bell"), { once: true });
knock("Olu");
knock("Mira");

// Removing: pass the same function, or use an AbortSignal for a group of listeners.
door.removeEventListener("knock", greet);
const controller = new AbortController();
door.addEventListener("knock", () => console.log("camera records"), { signal: controller.signal });
knock("Sam");
controller.abort();
knock("Lea");

// Cancelable events: a listener can veto the default action with preventDefault().
const form = new EventTarget();
form.addEventListener("submit", (event) => {
  if (event.detail.email === "") {
    event.preventDefault();
    console.log("blocked: email is empty");
  }
});
for (const email of ["", "ana@example.org"]) {
  const event = new CustomEvent("submit", { cancelable: true, detail: { email } });
  const proceed = form.dispatchEvent(event);   // false if a listener called preventDefault
  console.log(`submit "${email}": ${proceed ? "sent" : "not sent"}`);
}
text
-- Olu knocks
greet: a knock from Olu
bark
first-visitor bell
-- Mira knocks
greet: a knock from Mira
bark
-- Sam knocks
bark
camera records
-- Lea knocks
bark
blocked: email is empty
submit "": not sent
submit "ana@example.org": sent

Listeners run in the order they were added. { once: true } removes a listener after its first call. removeEventListener needs the same function object you added, which is why an inline arrow (like the bark one) can never be removed that way; passing a signal and later calling abort() removes every listener registered with it, the tidy way to clean up a component. A cancelable event lets a listener call preventDefault(), and the code that dispatched the event can check (here through dispatchEvent's return value) whether to go ahead. Browsers use exactly this for their built-in default actions: following a link, submitting a form, inserting a typed character.

Capture, target, bubble

On a page, an event aimed at an element does not only visit that element. It travels from document down the tree to the target (the capture phase), reaches the target, then travels back up to document (the bubble phase). A listener added normally runs during the target and bubble phases; one added with { capture: true } runs on the way down. So a click on a price span is also a click on its li, its ul, the body and the document, in that order on the way up.

Here is a small model of that algorithm in plain JavaScript (a simplification of the DOM standard's dispatch, written for this lesson), run on the tree in the figure:

javascript
// A small model of how the browser propagates an event through the DOM tree:
// capture (from the root down), target, then bubble (back up to the root).
class Node {
  constructor(name, parent = null, data = {}) {
    this.name = name;
    this.parent = parent;
    this.data = data;
    this.listeners = [];
  }
  on(type, handler, { capture = false } = {}) {
    this.listeners.push({ type, handler, capture });
  }
  closest(test) {                       // like element.closest(selector)
    for (let node = this; node; node = node.parent) if (test(node)) return node;
    return null;
  }
}

function dispatch(target, type) {
  const path = [];
  for (let node = target; node; node = node.parent) path.unshift(node); // root first
  const event = { type, target, stopped: false, stopPropagation() { this.stopped = true; } };
  const run = (node, phase, capture) => {
    for (const l of node.listeners) {
      if (l.type === type && l.capture === capture && !event.stopped) {
        l.handler({ ...event, currentTarget: node, phase, stopPropagation: () => (event.stopped = true) });
      }
    }
  };
  for (const node of path.slice(0, -1)) run(node, "capture", true);
  run(target, "target", true);
  run(target, "target", false);
  for (const node of path.slice(0, -1).reverse()) run(node, "bubble", false);
}

// document > body > ul#menu > li (one per dish) > span (the dish's name)
const documentNode = new Node("document");
const body = new Node("body", documentNode);
const menu = new Node("ul#menu", body);
const dishes = ["jollof rice", "pho", "arepas"].map((dish, i) => {
  const li = new Node(`li[${i}]`, menu, { dish });
  return new Node(`span[${i}]`, li);
});

const trace = (e) => console.log(`  ${e.phase.padEnd(7)} at ${e.currentTarget.name}`);
documentNode.on("click", trace, { capture: true });
body.on("click", trace);
menu.on("click", trace);
dishes[1].on("click", trace);

console.log("click on span[1]:");
dispatch(dishes[1], "click");

// Event delegation: ONE listener on the list handles clicks on every item,
// including items added later, by finding the item the click came from.
menu.on("click", (e) => {
  const li = e.target.closest((n) => n.name.startsWith("li"));
  if (li) console.log(`  delegated handler: you chose ${li.data.dish}`);
});
console.log("click on span[2]:");
dispatch(dishes[2], "click");

// stopPropagation: the body never hears about this click.
dishes[0].on("click", (e) => {
  console.log("  span[0] handles it and stops propagation");
  e.stopPropagation();
});
console.log("click on span[0]:");
dispatch(dishes[0], "click");
text
click on span[1]:
  capture at document
  target  at span[1]
  bubble  at ul#menu
  bubble  at body
click on span[2]:
  capture at document
  bubble  at ul#menu
  delegated handler: you chose arepas
  bubble  at body
click on span[0]:
  capture at document
  span[0] handles it and stops propagation

event.target is where the event happened; event.currentTarget is the element whose listener is running. The second click shows event delegation, the most useful consequence of bubbling: instead of a listener on every item, put one on their container and use event.target.closest(selector) to find which item was involved. It uses less memory, and it works for items added after the listener was registered. stopPropagation() ends the journey; use it sparingly, because other code (analytics, a menu that closes when you click elsewhere) may rely on hearing the event.

The events you will use most

EventFires whenNotes
clickan element is activated by mouse, touch, or Enter/Space on a buttonthe workhorse; works for keyboard users on real buttons
inputthe value of a text field, slider or select changes, on every keystrokefor live search and validation
changea field's value is committed (on blur, or on selection)for checkboxes, selects, file inputs
submita form is submittedlisten on the form, not the button; call preventDefault() to handle it yourself
keydowna key is pressedread event.key ("Enter", "Escape", "a")
pointerdown, pointermove, pointerupmouse, pen or touch interactionone family for every input device
focusin, focusoutan element gains or loses focusunlike focus and blur, these bubble, so they delegate
DOMContentLoadedthe HTML has been parsedmodule and defer scripts run just before it, so they rarely need it

In real browser code, delegation looks like this:

javascript
document.querySelector("#prices").addEventListener("click", (event) => {
  const row = event.target.closest("li[data-item]");
  if (!row) return;                            // a click between the rows
  showDetails(row.dataset.item);
});

Forms, fetch and preventDefault

The most common handler of all intercepts a form, sends its data with fetch, and shows the result without reloading the page:

javascript
const form = document.querySelector("#signup");
const status = document.querySelector("#status");

form.addEventListener("submit", async (event) => {
  event.preventDefault();                       // stop the browser's own page load
  const data = Object.fromEntries(new FormData(form));
  status.textContent = "Sending...";
  try {
    const response = await fetch("/api/signup", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
      signal: AbortSignal.timeout(10_000),
    });
    if (!response.ok) throw new Error(`server answered ${response.status}`);
    status.textContent = "Thank you! Check your email.";
    form.reset();
  } catch (err) {
    status.textContent = `Sorry, that didn't work (${err.message}).`;
  }
});

Everything from earlier lessons appears here: an async listener, await, try/catch, a timeout signal, Object.fromEntries. One detail catches many people: fetch rejects only when the request could not be made at all (no network, a timeout); a 404 or 500 answer still fulfils, which is why the code checks response.ok.

ExplanationH

Safe, fast and accessible

Cross-site scripting

The most important security rule in front-end code: never insert untrusted text as HTML. If a comment typed by a user is placed into the page with element.innerHTML = comment, and the comment contains markup with an event-handler attribute, the browser runs that code with all the powers of your page, including reading what the user sees and acting as them. This is cross-site scripting (XSS), for years among the most common vulnerabilities on the web. Use textContent for text, which never interprets markup, and createElement for structure. When you must build HTML as a string (on a server, or in a small templating helper), escape every value you did not write yourself:

javascript
// Building HTML from data safely: escape everything that didn't come from you.
const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
const escapeHtml = (value) => String(value).replaceAll(/[&<>"']/g, (ch) => ESCAPES[ch]);

// Markup we wrote ourselves is wrapped in SafeHtml; anything else gets escaped.
class SafeHtml {
  constructor(text) {
    this.text = text;
  }
  toString() {
    return this.text;
  }
}

// A tagged template: the function receives the literal parts and the values
// separately, so it can escape the values and leave the trusted markup alone.
function html(strings, ...values) {
  const render = (value) =>
    value instanceof SafeHtml ? value.text
    : Array.isArray(value) ? value.map(render).join("")
    : escapeHtml(value);
  let out = strings[0];
  values.forEach((value, i) => {
    out += render(value) + strings[i + 1];
  });
  return new SafeHtml(out);
}

const comments = [
  { author: "Ingrid", text: "Great recipe, thanks!" },
  { author: "mallory", text: '<img src=x onerror="stealCookies()">' },
];

const unsafe = comments.map((c) => `<li><b>${c.author}</b>: ${c.text}</li>`).join("\n");
const safe = html`<ul>${comments.map((c) => html`<li><b>${c.author}</b>: ${c.text}</li>`)}</ul>`;

console.log("UNSAFE (mallory's code would run if this went into innerHTML):");
console.log(unsafe);
console.log("SAFE:");
console.log(String(safe));
text
UNSAFE (mallory's code would run if this went into innerHTML):
<li><b>Ingrid</b>: Great recipe, thanks!</li>
<li><b>mallory</b>: <img src=x onerror="stealCookies()"></li>
SAFE:
<ul><li><b>Ingrid</b>: Great recipe, thanks!</li><li><b>mallory</b>: &lt;img src=x onerror=&quot;stealCookies()&quot;&gt;</li></ul>

The program also shows a feature you have not met yet: a tagged template. Writing a function name directly before a template literal, as in html`...` , calls the function with the literal's fixed text parts and its interpolated values separately, so the function can treat them differently: here, trusted markup passes through and every value is escaped. Templating libraries such as lit-html use the same idea. UI frameworks (React, Vue, Svelte, Angular) escape interpolated text automatically, which is one of their quiet benefits; they also give you an explicit, scary-sounding escape hatch for raw HTML, such as React's dangerouslySetInnerHTML. A Content Security Policy header adds a second line of defence by telling the browser which scripts may run at all.

Speed

  • Batch DOM changes. Reading a layout property (such as offsetHeight) right after changing the page forces the browser to recalculate layout immediately; doing that in a loop ("layout thrashing") can make a page crawl. Do all the reads, then all the writes, or build new elements off-page and insert them with one append.
  • Animate with requestAnimationFrame, which calls your function just before the next repaint, rather than with setInterval, and prefer CSS transitions where they suffice.
  • Keep handlers short. Every handler is a task on the one main thread (lesson eight); heavy work belongs in a Worker.

Accessibility

Use the element that means what you mean. A button element is focusable, works with the keyboard (Enter and Space) and is announced as a button by screen readers; a div with a click listener is none of those things until you add a role, a tabindex and key handling yourself. Links navigate, buttons act, forms have label elements. Accessible pages are also easier to test and to use on phones.

History & global context

From jQuery to frameworks

In the 2000s, browsers disagreed so much about the DOM and events that most sites used jQuery (2006) to smooth over the differences. As browsers converged on the standards (querySelector, classList, fetch and addEventListener all exist everywhere now), plain DOM code became practical again, and many small sites and widgets need nothing more.

Large applications face a different problem: keeping the page in step with changing data. Writing every update by hand is error-prone, so most teams use a framework in which you describe what the page should look like for the current state, and the framework works out the DOM changes. React (Meta, 2013) is the most widely used; Vue, Angular, Svelte and Solid take different approaches to the same problem; Web Components (custom elements and shadow DOM) are the browser's own standard component model. Frameworks are built on exactly the DOM and events of this lesson, and their documentation assumes you know them. Choose one when your interface has a lot of state; learn the platform underneath either way.

Beyond the DOM

The browser offers far more than the document, and MDN's Web APIs index is the map. A few you will meet early: localStorage keeps small strings per site across visits (it is synchronous and limited to a few megabytes, so store preferences there, not data); IndexedDB is a real client-side database for larger, structured data; URL and URLSearchParams parse and build addresses and query strings without error-prone string slicing; the History API lets single-page applications change the address bar without reloading; IntersectionObserver tells you when an element scrolls into view, the efficient way to load images lazily; and the Canvas, WebGL and WebGPU APIs draw graphics, from charts to games. Each is used through the same tools you now know: objects, methods, events, promises.

Common misconceptionsH

Common misconceptions

Misconception

"innerHTML is fine because my users are friendly." The danger is not your users but anyone who can get text into your page: a comment, a profile name, a URL parameter, data from another service. Treat all of it as untrusted.

Misconception

"fetch throws when the server returns an error." It fulfils for any HTTP response, including 404 and 500. Check response.ok (or response.status).

Misconception

"Each item in a list needs its own listener." With bubbling, one delegated listener on the container handles every item, including ones added later.

Misconception

"The DOM is slow, so frameworks are always faster." DOM operations are fast; unnecessary ones, and forced layouts, are slow. A framework helps by avoiding needless updates in complex interfaces, at the cost of code to download and run. Well-written plain DOM code is often the fastest option for small pages.

Exercises

Exercises

The first three are about the event API, which you can run in Node; the rest are about the browser.

1. In the browser: the DOM and events

Warm-upComputational

What number does this print?

const t = new EventTarget();
let count = 0;
t.addEventListener("ping", () => count++, { once: true });
t.addEventListener("ping", () => (count += 10));
t.dispatchEvent(new Event("ping"));
t.dispatchEvent(new Event("ping"));
console.log(count);

2. In the browser: the DOM and events

CoreComputational

What does this print?

const t = new EventTarget();
t.addEventListener("save", (e) => e.preventDefault());
console.log(t.dispatchEvent(new Event("save")), t.dispatchEvent(new Event("save", { cancelable: true })));

3. In the browser: the DOM and events

CoreComputational

How many times does this print hi?

const t = new EventTarget();
const same = () => console.log("hi");
t.addEventListener("x", same);
t.addEventListener("x", same);
t.addEventListener("x", () => console.log("hi"));
t.dispatchEvent(new Event("x"));

4. In the browser: the DOM and events

CoreHuman

A page has body > div > button. Listeners are added on the body (normal), on the div (one normal and one with { capture: true }) and on the button (normal). In what order do they run when the button is clicked?

Choose one

5. In the browser: the DOM and events

CoreComputational

Using the lesson's escapeHtml function, what does this print?

console.log(escapeHtml('5 > 3 & "x"'));

6. In the browser: the DOM and events

Warm-upHuman

A chat app shows each message's text inside a p element. Which is the right way to put the message in?

Choose one

7. In the browser: the DOM and events

StretchHuman

const response = await fetch("/api/missing") gets an HTTP 404 answer from the server. What happens?

Choose one

Further reading and resources