Event Delegation
Attach one listener to a parent instead of many listeners on children. Works for dynamic elements too.
Use event.target.closest(".selector") to match child.
Attach one listener to a parent instead of many listeners on children. Works for dynamic elements too.
Use event.target.closest(".selector") to match child.
// ❌ One listener per item
list.querySelectorAll('.item').forEach(i=>i.addEventListener('click',fn));
// ✅ One listener on parent
list.addEventListener('click', e=>{
const item=e.target.closest('.item');
if(!item) return;
item.classList.toggle('done');
});
More in JavaScript