JavaScript Interview Questions
JavaScript
Web DevelopmentFrontendBackendQuestion 17
What is event delegation in JavaScript?
Answer:
Event delegation is a technique where a single event listener is added to a parent element to manage events for multiple child elements. This approach leverages event bubbling, where an event starts from the target element and bubbles up to the ancestor elements. Event delegation is efficient because it reduces the number of event listeners needed and is particularly useful for managing dynamically added elements.
Here is an example demonstrating event delegation:
// HTML structure
// <ul id='parentList'>
// <li class='childItem'>Item 1</li>
// <li class='childItem'>Item 2</li>
// <li class='childItem'>Item 3</li>
// </ul>
// JavaScript code
let parentList = document.getElementById('parentList');
parentList.addEventListener('click', function(event) {
if (event.target && event.target.matches('li.childItem')) {
console.log('Item clicked:', event.target.textContent);
}
});
In this example, an event listener is added to the parent ul
element. When any li
element with the class childItem
is clicked, the event listener logs the text content of the clicked item. This approach efficiently manages the event handling for multiple child elements.