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:
✅ Answered with JavaScript best practices.- 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.
Recommended Links:
← Back to All Questions