Event Delegation
JS · DOM Manipulationsyntax
parent.addEventListener(event, (e) => {
if (e.target.matches(selector)) { ... }
});example
const todoList = document.querySelector("#todo-list");
todoList.addEventListener("click", (event) => {
const deleteBtn = event.target.closest(".delete-btn");
if (deleteBtn) {
const item = deleteBtn.closest(".todo-item");
item.remove();
}
});Note Attach one listener to a parent instead of many on children. Works for dynamically added elements too. Use closest() to find the nearest matching ancestor.