JavaScript Interview Question #68

Why is event delegation useful for dynamically created elements?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

A listener attached directly to existing child elements does not automatically attach itself to new child elements added later. With delegation, the stable ancestor already has the listener, and bubbled events from new descendants reach it.

Detailed Explanation

A listener attached directly to existing child elements does not automatically attach itself to new child elements added later. With delegation, the stable ancestor already has the listener, and bubbled events from new descendants reach it.

This can reduce listener-management code and memory overhead, but the handler should carefully confirm that the event originated from a relevant descendant.

Code Example

const table = document.querySelector("#products");

table.addEventListener("click", event => {
    const edit = event.target.closest("[data-action='edit']");

    if (!edit) return;

    console.log("Edit product", edit.dataset.id);
});

// Buttons added to #products later are also handled.