JAVASCRIPT
Implement Event Delegation for Efficient DOM Interaction
Master event delegation in JavaScript to efficiently handle events on multiple or dynamically added DOM elements with a single listener on a parent.
// HTML Structure
/*
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li><button>Add New Item</button></li>
</ul>
*/
const myList = document.getElementById('myList');
if (myList) {
myList.addEventListener('click', (event) => {
// Check if the clicked element is an <li>
if (event.target.tagName === 'LI') {
console.log(`Clicked on list item: ${event.target.textContent}`);
event.target.style.backgroundColor = '#e0e0e0'; // Example: change background
}
// Check if the clicked element is the 'Add New Item' button
else if (event.target.tagName === 'BUTTON' && event.target.textContent === 'Add New Item') {
const newItem = document.createElement('li');
newItem.textContent = `New Dynamic Item ${myList.children.length}`;
// Find the last LI and insert before it, or append if no LI exists.
const lastLi = myList.querySelector('li:last-of-type');
if (lastLi && lastLi.nextElementSibling && lastLi.nextElementSibling.tagName === 'BUTTON') {
myList.insertBefore(newItem, lastLi.nextElementSibling);
} else {
myList.appendChild(newItem);
}
console.log('Added a new item.');
}
});
}
// You can even add new items later, and the event listener will still work
// because it's attached to the parent <ul>.
// Example: setTimeout(() => {
// const newItem = document.createElement('li');
// newItem.textContent = 'Later Added Item';
// myList.appendChild(newItem);
// }, 2000);
How it works: Event delegation is a powerful technique where you attach a single event listener to a parent element instead of multiple listeners to individual child elements. When an event bubbles up from a child, the parent listener can check `event.target` to identify which specific child triggered the event and react accordingly. This significantly improves performance, especially with many dynamic elements, as new children automatically inherit event handling without needing new listeners.