Toolsnip

What is event delegation in JavaScript?

Javascript Interview Questions and Answers

Short Answer

Event delegation is a technique in JavaScript where you attach an event listener to a parent element instead of individual child elements.

Detailed Answer

This allows you to listen for events that bubble up from child elements to the parent element, which can improve performance and simplify your code.

Event delegation is especially useful when you have a large number of elements that need the same event listener, such as a list of items in a dropdown menu.

By attaching the event listener to the parent element, you can handle events for all child elements with a single event listener.

Event delegation works by using the 'event.target' property to determine which child element triggered the event, allowing you to take the appropriate action.

Overall, event delegation is a powerful technique in JavaScript for managing events on large sets of elements and can help improve the performance and readability of your code.