JAVASCRIPT

Implement Efficient Event Delegation for Dynamic DOM Elements

Learn to handle events for elements that are added to the DOM dynamically, or for a large number of similar elements, by attaching a single event listener to a parent element.

// Get the parent container where dynamic elements will reside
const parentContainer = document.getElementById('list-container');

// Add a single click event listener to the parent container
if (parentContainer) {
    parentContainer.addEventListener('click', function(event) {
        // Check if the clicked element (event.target) matches our desired child elements
        if (event.target && event.target.matches('.list-item')) {
            // Perform actions for the clicked .list-item
            console.log('Clicked item:', event.target.textContent);
            event.target.classList.toggle('highlight');
        }
    });
}

// Function to add dynamic items (simulate content loading)
function addDynamicItem(text) {
    const newItem = document.createElement('li');
    newItem.textContent = text;
    newItem.className = 'list-item';
    if (parentContainer) {
        parentContainer.appendChild(newItem);
    }
}

// Add some initial dynamic items
addDynamicItem('Item One');
addDynamicItem('Item Two');
addDynamicItem('Item Three');

// Even if more items are added later, the single event listener will still work
setTimeout(() => {
    addDynamicItem('Item Four (added later)');
}, 2000);

/*
Example HTML structure:
<ul id="list-container">
    <!-- Dynamic li.list-item elements will be added here -->
</ul>
*/
How it works: Event delegation is a powerful technique for handling events on multiple child elements, especially when those elements are added to the DOM dynamically after the page loads. Instead of attaching individual listeners to each child, a single listener is attached to a common parent. When an event bubbles up to the parent, `event.target` identifies the actual element that was clicked. The `matches()` method then efficiently checks if `event.target` is the element type we're interested in, allowing for efficient and scalable event handling.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs