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.
closest can climb past your container, so check container.contains(match) when containers can be nested or when the selector is generic.
Use data-action attributes to route different buttons in one handler: const action = event.target.closest("[data-action]")?.dataset.action.
Delegation needs events that bubble. For focus use focusin/focusout; mouseenter/mouseleave cannot be delegated, but mouseover/mouseout can.
Delegation reduces setup work and avoids re-attaching listeners after re-rendering a list with innerHTML, which is why many frameworks delegate at the root internally.
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).
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.
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
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.
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 explanationevent 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 predictionevent 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.
Debuggingevent 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 generationevent 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 reviewevent 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.