JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 12: Events and InteractionLesson 59 of 150About 45 minutes

Lesson 59: Event delegation

01Opening question

A list has 500 rows and new rows arrive every minute. Do you really need 500 listeners?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

One listener on the list handles clicks on every item because clicks bubble up. This is event delegation.

const list = document.querySelector("#list");
list.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (item) console.log("Picked", item.textContent);
});
list.children[1].click();

03Objective and prerequisites

Learning objective: Handle events for many (and future) child elements with one listener on a parent, using event.target.closest and data attributes.

You need: Lesson 58: Event bubbling and capturing, Lesson 55: Updating styles, attributes and classes

Skills practised: Events, Event delegation.

04Explanation

Event delegation means putting one listener on a parent instead of one on every child. Clicks on the children bubble up to the parent.

Inside the listener, event.target tells you which child was clicked. event.target.closest("li") finds the nearest matching ancestor (or the element itself).

Delegation also works for elements added later, because the listener lives on the parent, which is already there.

Store what each child represents in a data- attribute (data-id="7") and read it with dataset in the shared handler.

05Definitions

Event delegation
Handling events for many child elements with one listener on a common ancestor.
closest
A method that returns the element itself or its nearest ancestor matching a selector, or null.
dataset
An object with an element's data- attributes, such as data-id read as dataset.id.
Action attribute
A data- attribute such as data-action="delete" used to route clicks in a delegated handler.
contains
A method that reports whether a node is inside another node (or is that node).

Open the full glossary

06Visual learning object

Event delegation explorer. Click items, nested icons and newly added rows, and see how one parent listener resolves each click with closest.

Loading the interactive object…

Open the full Event delegation explorer page with its guided experiment.

07Examples

ex-059-01One listener for a list Browser page (sandboxed preview)

closest finds the li even when an inner element is clicked.

const todos = document.querySelector("#todos");
todos.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (!item) return;
  console.log("Clicked item", item.dataset.id);
});
todos.querySelector("b").click();
todos.children[1].click();
Sample input
None
Expected output
Clicked item 1 Clicked item 2
Common mistake
Using event.target.dataset.id and getting undefined when the b element is clicked.
Try this
Add a third li from code and click it.
Source
examples/ex-059-01-delegated-list.js

ex-059-02Works for new elements Browser page (sandboxed preview)

Rows added after the listener still work, because the listener is on the parent.

const feed = document.querySelector("#feed");
feed.addEventListener("click", (event) => {
  const post = event.target.closest(".post");
  if (post) console.log("Open post", post.dataset.id);
});
for (const id of [10, 11]) {
  const li = document.createElement("li");
  li.className = "post";
  li.dataset.id = id;
  li.textContent = "Post " + id;
  feed.append(li);
}
feed.lastElementChild.click();
Sample input
None
Expected output
Open post 11
Common mistake
Adding listeners in a loop before the elements exist.
Try this
Re-render the list with innerHTML and click again.
Source
examples/ex-059-02-future-items.js

ex-059-03Routing with data-action Browser page (sandboxed preview)

One handler can run different actions based on a data attribute.

const cart = document.querySelector("#cart");
const qty = { 7: 1 };
const actions = {
  inc: (id) => { qty[id]++; console.log("qty", qty[id]); },
  remove: (id) => { delete qty[id]; console.log("removed", id); }
};
cart.addEventListener("click", (event) => {
  const button = event.target.closest("[data-action]");
  if (!button) return;
  const id = button.closest("li").dataset.id;
  actions[button.dataset.action](id);
});
cart.querySelector('[data-action="inc"]').click();
cart.querySelector('[data-action="remove"]').click();
console.log(JSON.stringify(qty));
Sample input
None
Expected output
qty 2 removed 7 {}
Common mistake
Writing a long if/else chain over button text instead of using data-action.
Try this
Add a dec action that never goes below 1.
Source
examples/ex-059-03-actions.js

ex-059-04Staying inside the container Browser page (sandboxed preview)

closest can match outside your list, so check contains.

const inner = document.querySelector("#inner");
inner.addEventListener("click", (event) => {
  const row = event.target.closest(".row");
  console.log(row ? row.id : null, inner.contains(row));
  const safe = row && inner.contains(row) ? row : null;
  console.log("safe:", safe);
});
inner.querySelector(".x").click();
Sample input
None
Expected output
outside false safe: null
Common mistake
Trusting closest without checking that the match belongs to the list.
Try this
Change the selector to .x and predict both lines.
Source
examples/ex-059-04-contains-check.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Clicks on the badge

Find the row with closest.

let opened = null;
document.querySelector("#inbox").addEventListener("click", (event) => {
  opened = event.target.dataset.id;
});
document.querySelectorAll(".badge")[1].click();
console.log("Opened:", opened);

Delegated delete buttons

Remove items with one listener.

const tags = document.querySelector("#tags");
// TODO: one listener on #tags; when a .del button is clicked, remove its li
tags.querySelectorAll(".del")[0].click();
console.log(tags.children.length, tags.firstElementChild.firstChild.textContent.trim());

A star rating

Delegate clicks and render from a value.

// Keep let rating = 0. One listener on #stars: clicking a star sets
// rating to its data-value and fills stars 1..rating with ★ (others ☆).
// Then click star 3 and log the stars' text joined with "".
let rating = 0;

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <ul id="l"></ul>
const l = document.getElementById("l");
l.addEventListener("click", (e) => console.log("got", e.target.textContent));
l.innerHTML = "<li>A</li><li>B</li>";
l.lastElementChild.click();

What is printed?

10Debugging investigation

New rows ignore clicks

Rows that exist when the page loads can be selected. Rows added with the Add button cannot.

const list = document.getElementById("list");
let selected = "none";
for (const li of list.querySelectorAll("li")) {
  li.addEventListener("click", () => { selected = li.textContent; });
}
document.getElementById("add").addEventListener("click", () => {
  const li = document.createElement("li");
  li.textContent = "Row " + (list.children.length + 1);
  list.append(li);
});
document.getElementById("add").click();
list.lastElementChild.click();
console.log("selected: " + selected);

More cases in the Debugging Detective Laboratory

11Practical scenario

Tables with thousands of rows

An admin dashboard lists thousands of orders with Edit and Refund buttons. Instead of thousands of listeners, the table body has one click listener that reads data-action and the row's data-id, so re-rendering after a filter needs no listener setup at all.

const rows = 5000;
console.log("listeners without delegation:", rows * 2);
console.log("listeners with delegation:", 1);

12Knowledge check

1. What is event delegation?

  • Adding a listener to every child
  • Handling children's events with one listener on an ancestor
  • Delaying events
  • Passing events to a worker

2. Why does delegation work for elements added later?

  • The browser copies listeners to new elements
  • The listener is on the parent, which receives the bubbled event
  • New elements inherit onclick
  • It does not work for them

3. What does closest return when no ancestor matches?

  • undefined
  • null
  • The document
  • An empty list

4. Why is id sometimes undefined?

list.addEventListener("click", (e) => {
  const id = e.target.dataset.id;
});
  • The click can land on an element inside the li
  • dataset is not supported
  • id must be a number
  • The listener must be on document

5. Which event cannot be delegated because it does not bubble?

  • click
  • input
  • mouseenter
  • keydown

6. A list is re-rendered with innerHTML after every filter. Which listener setup is simpler?

  • Re-add listeners to each new li after rendering
  • One delegated listener on the list, added once
  • onclick attributes in the HTML strings
  • A timer that checks for clicks

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Clicks on the badge: Prints Opened: a2; Clicking the li itself works
  • Delegated delete buttons: Prints 2 html; Clicking text removes nothing; Only one listener
  • A star rating: Prints three filled stars; rating is the number 3; Clicking star 5 fills all

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-12-events-and-interaction/lesson-059-event-delegation/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Delegation puts one listener on a parent for many children.
  • closest finds the relevant element from event.target.
  • It works for children added later.
  • data- attributes carry ids and actions to the shared handler.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation event delegation
Context: I am learning event delegation in JavaScript.
Task: Explain event delegation with a list, closest and data attributes.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction event delegation drill
Context: I have practised event delegation.
Task: Give me six delegation programs with nested elements and ask what each logs.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging event delegation bug
Context: My delegated handler gets undefined when I click the icon inside a button.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation event delegation practice
Context: I finished the event delegation exercises.
Task: Create three delegation exercises, including one with rows added later.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review event delegation review
Context: Here is my code that uses event delegation.
Task: Review my list code and show where one delegated listener could replace many.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.