JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is event delegation in JavaScript?

Asked on Aug 11, 2024

Answer

Event delegation is a technique in JavaScript that allows you to manage events efficiently by setting a single event listener on a parent element to handle events triggered by its child elements. This is particularly useful for handling events on dynamically added elements.
<!-- BEGIN COPY / PASTE -->
        document.getElementById("parent").addEventListener("click", function(event) {
            if (event.target && event.target.matches("button.child")) {
                console.log("Child button clicked!");
            }
        });
        <!-- END COPY / PASTE -->
Additional Comment:
  • The event listener is added to the "parent" element.
  • Inside the event handler, "event.target" is used to determine which child element triggered the event.
  • The "matches" method checks if the clicked element matches the specified selector, in this case, "button.child".
  • This approach reduces the number of event listeners and is efficient for managing events on multiple child elements.
✅ Answered with JavaScript best practices.
← Back to All Questions