With Delegation
With Delegation
Section titled “With Delegation”Introduction
Section titled “Introduction”Event delegation attaches a single listener to a parent element and uses the event’s target to determine which child was interacted with.
How It Works
Section titled “How It Works”// ✅ Single listener on parentdocument.querySelector('ul').addEventListener('click', (e) => { const item = e.target.closest('li'); if (item) { console.log('Item clicked:', item.textContent); }});// Works for all items — existing and future!Visual Explanation
Section titled “Visual Explanation”flowchart LR subgraph "With Delegation ✅" C["<ul> (1 listener)"] D["1000 list items"] E["Event bubbles up to <ul>"] end
C --> D D --> EBenefits
Section titled “Benefits”- ✅ Single listener vs thousands — less memory
- ✅ Works for dynamically added elements
- ✅ Easier to maintain and update
- ✅ Better performance
Summary
Section titled “Summary”- One parent listener handles all children via event bubbling
- Use
e.target.closest()to identify the specific target - Works for dynamically added elements
- Reduces memory usage and improves performance