The browser
Event delegation and closest
One listener on the parent instead of a hundred on the children, thanks to bubbling.
Why it exists
A catalog has 500 products with a "Buy" button. Attaching 500 handlers means 500 functions in memory, and it still isn't enough: load more products or redraw the list after filtering, and the new buttons have no handlers, so you have to remember to attach them. Delegation fixes both problems: there's one handler, it lives on a container that doesn't change, and it serves all the children, present and future.
Where it's used
- Lists and tables: "Buy", "Delete", "Edit" on every row.
- Menus, tabs, toolbars: lots of buttons, one handler.
- Lists that get redrawn: an infinite feed, search results, a todo list.
- Frameworks: React attaches one handler to the app's root and hands events to components itself.
Syntax
container.addEventListener("click", (event) => {
const button = event.target.closest(".selector");
if (!button) return; // missed
// button.dataset… tells you what to work with
});Examples
// How closest finds the button: it climbs from the element through its parents
function closest(node, tag) {
while (node && node.tag !== tag) node = node.parent;
return node ?? null;
}
const list = { tag: "ul", parent: null };
const button = { tag: "button", parent: list, toy: "mouse" };
const icon = { tag: "b", parent: button };
closest(icon, "button").toy; // → "mouse" — clicked the icon, found the button
closest(list, "button"); // → null — the click missed the buttonsconst cart = [];
const actions = {
add: (toy) => cart.push(toy),
remove: (toy) => cart.splice(cart.indexOf(toy), 1),
};
// In a browser, button would come from event.target.closest("button"),
// and action and toy from button.dataset
function handleClick(button) {
if (!button) return;
actions[button.action]?.(button.toy);
}
handleClick({ action: "add", toy: "mouse" });
handleClick({ action: "add", toy: "feather" });
handleClick({ action: "remove", toy: "mouse" });
handleClick(null); // the click missed the buttons
cart; // → ["feather"]data-action says what to do// A tiny model of bubbling: the event goes from the target up through the parents
function dispatchClick(target) {
for (let node = target; node; node = node.parent) {
node.onClick?.({ target, currentTarget: node });
}
}
const bought = [];
const list = { tag: "ul", parent: null };
list.onClick = (event) => bought.push(event.target.toy);
// The button was "added" after subscribing
const later = { tag: "button", parent: list, toy: "laser pointer" };
dispatchClick(later);
bought; // → ["laser pointer"]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
It works thanks to bubbling: an event that happens on an element then fires on each of its ancestors in turn, up to document. So a click on an icon inside a button inside a list reaches a handler on the list.
Inside the handler:
- event.target is the deepest element the click landed on: an icon, a label, the button itself or an empty spot in the list;
target.closest("selector")checks the element itself and climbs through its parents until it finds a match; if there's none, it returns null;- event.currentTarget is the container the handler is attached to.
Buttons often get data- attributes (data-action="remove", data-id="42"), and one handler uses them to decide what to do. Almost every large interface works this way.
Traps
How it differs from…
addEventListener: subscribing to an eventA handler on each element is simple and clear for two or three buttons. Delegation is the same addEventListener, but just one, on the container: fewer functions, and it works for elements added later.
When to pick something else
For one or two permanent buttons, delegation only adds confusion: attach the handler straight to the button. The same goes for events that don't bubble (focus, mouseenter): use their bubbling counterparts or attach to the element itself.