JAVASCRIPT
Implement Event Delegation on a Parent Element
Learn event delegation in JavaScript, attaching a single event listener to a parent element to manage events for dynamically added child elements efficiently.
// Assume an HTML structure like: <ul id="myList"><li>Item 1</li><li>Item 2</li></ul>
const myList = document.getElementById('myList');
if (myList) {
myList.addEventListener('click', function(event) {
// Check if the clicked element is a list item or a descendant of a list item
if (event.target.tagName === 'LI') {
console.log('List item clicked:', event.target.textContent);
event.target.classList.toggle('selected');
}
// You can also target specific child elements with matches()
if (event.target.matches('.delete-btn')) {
console.log('Delete button clicked for:', event.target.closest('li').textContent);
event.target.closest('li').remove();
}
});
// Add a new list item dynamically to demonstrate event delegation
const newItem = document.createElement('li');
newItem.textContent = 'Dynamically Added Item';
const deleteButton = document.createElement('button');
deleteButton.className = 'delete-btn';
deleteButton.textContent = 'X';
newItem.appendChild(deleteButton);
myList.appendChild(newItem);
console.log('Event listener attached to parent list.');
} else {
console.log('List element with ID "myList" not found.');
}
How it works: This snippet demonstrates event delegation, a powerful technique where a single event listener is attached to a parent element instead of individual child elements. When an event occurs on a child, it "bubbles up" to the parent. The listener then identifies the actual target using `event.target` and performs actions. This is particularly efficient for lists with many items or when items are added/removed dynamically, as the listener doesn't need to be re-attached to new elements.