Delegate events to a shared ancestor
Quick answer
Delegation attaches one handler to a stable ancestor. For a bubbling click, inspect the target, find the relevant ancestor with closest(selector), and confirm it belongs to the intended container using contains. This handles children added later. Check that the target is an Element before using closest.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const list=document.createElement("div"),b=document.createElement("button"),s=document.createElement("span");b.dataset.action="save";b.append(s);list.append(b);list.addEventListener("click",e=>{const hit=e.target instanceof Element?e.target.closest("button[data-action]"):null;if(hit&&list.contains(hit))console.log(hit.dataset.action);});s.click();Expected console output:
saveclosest climbs from the span to the matching button.
const box=document.createElement("div"),inside=document.createElement("button"),outside=document.createElement("button");box.append(inside);console.log(box.contains(inside),box.contains(outside),box.contains(box));Expected console output:
true false trueContainment includes the receiver itself.
Common mistake
Checking only the target tag misses clicks on nested icons or spans. Avoid delegating an event that does not bubble unless you deliberately use capture.
Practice
Add a new labeled button after registering the listener and verify that clicks on its inner span work.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Delegate events to a shared ancestor — Knowledge Check
Apply the concept and predict the browser example behavior.
Why use closest in a delegated click handler?
Why verify containment after closest?
What advantage does delegation offer for dynamically added buttons?
What is the exact console output in Delegate events to a shared ancestor example 1?
const list=document.createElement("div"),b=document.createElement("button"),s=document.createElement("span");b.dataset.action="save";b.append(s);list.append(b);list.addEventListener("click",e=>{const hit=e.target instanceof Element?e.target.closest("button[data-action]"):null;if(hit&&list.contains(hit))console.log(hit.dataset.action);});s.click();What is the exact console output in Delegate events to a shared ancestor example 2?
const box=document.createElement("div"),inside=document.createElement("button"),outside=document.createElement("button");box.append(inside);console.log(box.contains(inside),box.contains(outside),box.contains(box));