JavaScript Interview Question #67

What is event delegation?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

Event delegation registers a listener on a common ancestor instead of adding a separate listener to every child element. The handler examines event.target, often with closest, to determine which relevant descendant triggered the event.

Detailed Explanation

Event delegation registers a listener on a common ancestor instead of adding a separate listener to every child element. The handler examines event.target, often with closest, to determine which relevant descendant triggered the event.

Delegation works because many events bubble. It is useful for large lists and dynamically inserted elements because newly added matching children can work without registering new individual listeners.

Code Example

const list = document.querySelector("#userList");

list.addEventListener("click", event => {
    const button = event.target.closest(".delete-user");

    if (!button || !list.contains(button)) {
        return;
    }

    const userId = button.dataset.userId;
    console.log("Delete user:", userId);
});