What is Event Delegation in JavaScript and why is it useful for performance?
Theoretical ConceptEvent delegation is a pattern of handling events at a parent element instead of attaching listeners to multiple child elements.
Comprehensive AnswerEvent delegation relies on the mechanism of event bubbling: when an event occurs on a DOM element, it bubbles upward through all its parent ancestors in the DOM tree. By attaching a single event listener to a common ancestor element and inspecting event.target, we can manage events for dozens or hundreds of child elements (including dynamic elements added in the future), dramatically lowering browser memory consumption.
Code Demonstration// Single listener on parent <ul> instead of 100 <li> listeners
document.getElementById('studentList').addEventListener('click', (event) => {
const target = event.target.closest('li');
if (target && target.dataset.id) {
console.log("Selected Student ID:", target.dataset.id);
}
});
In an infinite-scrolling feed rendering thousands of comment cards, attaching individual click handlers to each button crashes mobile browsers, whereas a single delegated parent listener remains lightning-fast.
Related follow-up question: What is the difference between event bubbling and event capturing?