Lesson 10 of 12 · 11 min · JavaScript in the browser

The DOM and events

Covers: DOM and JavaScript in current browsers. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • What the DOM is and how to select and change elements
  • Create and insert elements safely, avoiding XSS
  • Add event listeners and use the event object
  • Event bubbling, capturing and delegation
  • preventDefault, debounce, throttle, passive listeners and cleanup

In simple words

When the browser reads your HTML, it builds a live model of the page in memory called the DOM, a tree of objects, one for every element. JavaScript can read and change that tree, and every change shows up on screen. Events are the page telling your code that something happened, such as a click, a key press or a form submit, so you can react.

Words to know

  • DOM: the Document Object Model, the browser's tree of objects for the page.
  • Event: a signal that something happened, such as a click.
  • Event listener: a function that runs when a chosen event happens.
  • Bubbling: an event travelling upward from the element where it happened through its parents.

Selecting elements

const title = document.querySelector("h1");                  // first match, or null
const buttons = document.querySelectorAll(".btn");            // a static NodeList of all matches
const form = document.getElementById("signup");
const card = button.closest(".card");                         // nearest ancestor (or self) matching
const first = list.firstElementChild;
const items = [...list.children];                             // convert to a real array

for (const b of buttons) b.disabled = true;                   // NodeLists are iterable
buttons.forEach((b) => b.classList.add("big"));

querySelector takes any CSS selector (including :has(), [data-id="5"]). Check for null before using the result. Script tags with defer (or type="module") run after the DOM is parsed, so the elements exist; otherwise wait for DOMContentLoaded.

Changing elements

title.textContent = "Welcome, Asha";            // safe: text only
card.classList.add("active");                   // also remove, toggle, contains
card.classList.toggle("open", isOpen);
card.setAttribute("aria-expanded", "true");     // attributes
card.dataset.orderId = "101";                   // data-order-id="101"
card.style.setProperty("--progress", "60%");    // set a CSS variable, prefer classes
img.src = "/photo.jpg";                         // properties
input.value = "";
card.hidden = true;

Creating elements, and XSS

const li = document.createElement("li");
li.textContent = order.customer;                // safe: the text cannot become HTML
li.dataset.id = order.id;
list.append(li);                                // also prepend, before, after, replaceWith, remove()

list.replaceChildren(...orders.map(renderOrder));   // replace all children in one step

innerHTML is dangerous with untrusted text. If a user's name is <img src=x onerror=stealCookies()> and you write it with innerHTML, the script runs: cross-site scripting (XSS).

el.innerHTML = `<b>${user.name}</b>`;            // dangerous if user.name comes from anywhere untrusted
el.textContent = user.name;                      // safe

Rules: use textContent for text; create elements with createElement; use <template> elements for repeated markup; and if you must insert HTML, sanitise it with a library such as DOMPurify or the Sanitizer API, and enable a Content Security Policy. Frameworks such as React escape text for you.

Event listeners

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

input.addEventListener("input", (event) => {          // fires on every change
  console.log(event.target.value);
});

form.addEventListener("submit", (event) => {
  event.preventDefault();                              // stop the browser's default submit and page reload
  const data = Object.fromEntries(new FormData(form));
  save(data);
});

document.addEventListener("keydown", (event) => {
  if (event.key === "Escape") closeDialog();
});
  • Prefer addEventListener over onclick="..." attributes (no inline JavaScript, several listeners per event).
  • Common events: click, dblclick, input, change, submit, focus, blur, keydown, keyup, pointerdown, pointermove, scroll, resize, DOMContentLoaded, load, visibilitychange, online, offline.
  • Use pointer events (pointerdown) for mouse, touch and pen together.
  • On a form, listen to submit (not click on the button), so Enter works too.
  • { once: true } runs the listener once; { signal } lets an AbortController remove it.

The event object

Property Meaning
event.target the element where the event started (the deepest one clicked)
event.currentTarget the element the listener is attached to
event.type "click", "keydown"...
event.key, event.code keyboard events (key is the character, code the physical key)
event.preventDefault() cancel the default action (follow a link, submit a form)
event.stopPropagation() stop the event from bubbling up (use rarely)
event.clientX, clientY pointer position
event.isTrusted true for real user actions, false for script-created events

Bubbling, capturing and delegation

Most events bubble: after the target element, the event goes to its parent, grandparent and up to document. (There is an earlier capturing phase going down, rarely used: addEventListener(type, fn, { capture: true }).)

<ul id="orders">
  <li data-id="101">Order 101 <button class="cancel">Cancel</button></li>
  <li data-id="102">Order 102 <button class="cancel">Cancel</button></li>
</ul>

Instead of adding a listener to every button, which is slow for long lists and misses buttons added later, attach one listener to the parent and use event.target: event delegation.

document.getElementById("orders").addEventListener("click", (event) => {
  const button = event.target.closest(".cancel");
  if (!button) return;                                     // click was elsewhere
  const id = button.closest("li").dataset.id;
  cancelOrder(id);
});

Benefits: fewer listeners (memory), and it works for elements added later. Caution: some events do not bubble (focus, blur, mouseenter; use focusin, focusout, mouseover) and closest may match an element outside the container, so check container.contains(button) if needed. Frameworks, including React, use delegation internally.

Frequent events: debounce and throttle

input, scroll, resize and pointermove fire many times a second; doing heavy work in each is wasteful.

function debounce(fn, ms) {
  let timer;
  return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); };
}
search.addEventListener("input", debounce((e) => runSearch(e.target.value), 300));   // after the user pauses

function throttle(fn, ms) {
  let last = 0;
  return (...args) => { const now = performance.now(); if (now - last >= ms) { last = now; fn(...args); } };
}
window.addEventListener("scroll", throttle(updateProgressBar, 100), { passive: true });   // at most every 100 ms

Debounce waits for a pause (search boxes, auto-save, resize end); throttle limits the rate (scroll, drag). Add { passive: true } to scroll and touch listeners to tell the browser you will not call preventDefault(), so scrolling stays smooth. Better still, use IntersectionObserver (is it visible?), ResizeObserver and CSS (position: sticky, scroll snap, scroll-timeline) instead of scroll handlers.

Custom events

const event = new CustomEvent("order:paid", { detail: { id: 101 }, bubbles: true });
card.dispatchEvent(event);
document.addEventListener("order:paid", (e) => console.log(e.detail.id));

Useful for decoupling components (and the basis of Web Components).

Removing listeners and avoiding leaks

Listeners keep their functions (and everything they capture) alive. Remove them when the element or component goes away:

const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
window.addEventListener("keydown", onKey, { signal: controller.signal });
controller.abort();                              // removes both

(removeEventListener(type, sameFunction) also works but requires the same function reference, so anonymous arrows cannot be removed.) Removing the element with el.remove() drops its own listeners once nothing references the element; listeners on window or document do not go away by themselves.

A small complete example

<input id="q" type="search" placeholder="Search courses" aria-label="Search courses">
<ul id="results" aria-live="polite"></ul>
<script type="module">
  const q = document.getElementById("q");
  const results = document.getElementById("results");
  const courses = ["Java", "Python", "SQL", "Power BI", "React"];

  q.addEventListener("input", debounce(() => {
    const text = q.value.trim().toLowerCase();
    const matches = courses.filter((c) => c.toLowerCase().includes(text));
    results.replaceChildren(...matches.map((c) => Object.assign(document.createElement("li"), { textContent: c })));
  }, 200));

  function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }
</script>

Common mistakes

  • innerHTML with user data (XSS).
  • Listeners on hundreds of elements instead of delegation.
  • Forgetting preventDefault() on form submit handlers (the page reloads).
  • Confusing event.target and event.currentTarget.
  • Heavy work in scroll and input handlers with no debounce or passive option.
  • Never removing listeners on window and document.
  • Using click on divs instead of buttons and links.

Try it yourself

  1. Build a to-do list: add items from a form, mark done on click, and delete with a button, using event delegation on the list.
  2. Show that innerHTML with <img src=x onerror=alert(1)> runs a script, then switch to textContent.
  3. Add a debounced search box that filters a list.
  4. Add a keyboard shortcut (/ focuses search, Escape clears) and make sure it does not fire while typing in inputs.
  5. Use an AbortController to remove several listeners at once.

Check yourself

What is event delegation and why use it?

Attaching one listener to a parent and using event.target (often with closest) to handle events from its children. It needs fewer listeners and works for elements added later.

What is the difference between event.target and event.currentTarget?

target is the element where the event originated; currentTarget is the element the listener is attached to.

Why prefer textContent to innerHTML for user data?

textContent inserts text only, while innerHTML parses HTML and can execute malicious scripts (XSS).

What do debounce and throttle do?

Debounce delays a function until events stop for a given time; throttle lets it run at most once per interval.

Interview questions

Explain event bubbling and capturing.

Events travel in three phases: capturing from window down to the target, the target itself, and bubbling back up through the ancestors. Listeners run during bubbling by default, or capturing if you pass capture: true.

What does preventDefault() do and how does it differ from stopPropagation()?

preventDefault() cancels the browser's default action for the event (such as following a link); stopPropagation() stops the event from reaching other listeners on ancestor elements.

How do you avoid memory leaks with event listeners?

Remove listeners when elements or components are destroyed (use AbortController signals or removeEventListener), especially on window and document, and avoid capturing large objects in long-lived handlers.

Summary

  • The DOM is a live tree of the page; select with querySelector, change with classList, textContent and attributes.
  • Use textContent and createElement, never innerHTML with untrusted data.
  • Attach events with addEventListener; know target versus currentTarget, bubbling and delegation, and preventDefault.
  • Debounce or throttle frequent events, use passive listeners and observers, and clean up listeners.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.