Event Bubbling & Delegation
MediumIn plain terms
Events bubble from target to root. Use event delegation: attach one listener on parent, check e.target. Efficient for dynamic lists.
What you need to know
- •Bubbling: child to parent
- •Delegation: parent handler
- •e.target vs e.currentTarget
Try it yourself
Copy the code below and run it in your browser console or a code editor:
list.addEventListener('click', (e) => { if (e.target.matches('li')) console.log(e.target.textContent); });Learn more
Dive deeper with these trusted resources: