Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 4 of 10 · DOM Manipulation and Events
Interview question

What is event delegation and why is it useful? Event delegation क्या है और यह क्यों उपयोगी है?

Answer

Event delegation is a technique of attaching a single event listener to a parent element instead of individual listeners on each child, relying on event bubbling to catch events from children.

// WITHOUT delegation - a listener per item, doesn't work for future items
const items = document.querySelectorAll('.list-item');
items.forEach(item => {
    item.addEventListener('click', () => console.log('Item clicked'));
});
// Problem: new items added later won't have this listener

// WITH delegation - one listener on the parent
const list = document.querySelector('.list');
list.addEventListener('click', function(event) {
    if (event.target.classList.contains('list-item')) {
        console.log('Item clicked:', event.target.textContent);
    }
});

// This automatically works for dynamically added items too
const newItem = document.createElement('li');
newItem.className = 'list-item';
newItem.textContent = 'New Item';
list.appendChild(newItem); // click on this works without adding a new listener

// Using closest() for more robust matching (handles nested elements)
list.addEventListener('click', function(event) {
    const item = event.target.closest('.list-item');
    if (item) {
        console.log('Item clicked:', item.textContent);
    }
});
BenefitExplanation
Better performanceOne listener instead of hundreds for large lists
Works with dynamic contentNew elements automatically covered, no re-binding needed
Less memory usageFewer listener objects retained in memory

Event delegation एक technique है जिसमें हर child पर अलग listener लगाने की बजाय parent पर एक ही listener लगाया जाता है, event bubbling का उपयोग करके।

// बिना delegation
const items = document.querySelectorAll('.list-item');
items.forEach(item => {
    item.addEventListener('click', () => console.log('Item clicked'));
});
// Problem: बाद में added नए items पर listener नहीं होता

// Delegation के साथ - parent पर एक listener
const list = document.querySelector('.list');
list.addEventListener('click', function(event) {
    if (event.target.classList.contains('list-item')) {
        console.log('Item clicked:', event.target.textContent);
    }
});

// Dynamically added items के लिए भी automatically काम करता है
const newItem = document.createElement('li');
newItem.className = 'list-item';
list.appendChild(newItem);

// closest() से robust matching
list.addEventListener('click', function(event) {
    const item = event.target.closest('.list-item');
    if (item) console.log('Item clicked:', item.textContent);
});
फायदाविवरण
बेहतर performanceबड़ी lists के लिए एक ही listener
Dynamic content के साथ काम करता हैनए elements automatically cover होते हैं
कम memory usageकम listener objects memory में

Was this answer clear?