Event Delegation Implementation Examples
Real implementation examples of event delegation.
Event Delegation Implementation Examples
List Items
document.querySelector("#list").addEventListener("click", (e) => { if (e.target.matches(".list-item")) { console.log("Clicked:", e.target.dataset.id); } });
Table Rows
document.querySelector("table").addEventListener("click", (e) => { const row = e.target.closest("tr"); if (row) console.log("Row:", row.dataset.id); });
Menu Items
document.querySelector(".menu").addEventListener("click", (e) => { const item = e.target.closest(".menu-item"); if (item) handleMenuClick(item.dataset.action); });
Dynamic List
const list = document.querySelector("#dynamic-list"); list.addEventListener("click", (e) => { if (e.target.matches(".delete-btn")) { e.target.closest("li").remove(); } }); // adding new items: no need to add listeners list.innerHTML += "<li>New item <button class='delete-btn'>Delete</button></li>";
The Takeaway
Examples: list items (e.target.matches), table rows (e.target.closest('tr')), menu items (e.target.closest('.menu-item')), and dynamic lists (works for newly added items). Use closest() to find the relevant parent element when the click is on a child (like a button inside a row).
Add one listener on the ul: ul.addEventListener('click', e => { if (e.target.matches('.list-item')) handle(e.target); }). Check e.target to determine which item was clicked. Works for dynamic items.
When the click is on a child (like a button inside a row), use e.target.closest('tr') to find the relevant parent: const row = e.target.closest('tr'); if (row) handle(row). This finds the nearest ancestor matching the selector.
Add one listener on the list: list.addEventListener('click', e => { if (e.target.matches('.delete-btn')) e.target.closest('li').remove(); }). New items with delete buttons work automatically without adding new listeners.
closest() finds the nearest ancestor (including the element itself) that matches a CSS selector. For example, e.target.closest('.menu-item') finds the menu item even if the click was on a child element inside the menu item.
Yes. Use e.target.closest('li') to find the list item even if the click was on a span or button inside it. closest() traverses up from e.target to find the matching ancestor.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

