How do you use event delegation for a data table in JavaScript?
table.addEventListener('click', e => { const row = e.target.closest('tr'); if (e.target.matches('.sort-btn')) sortTable(e.target.dataset.column); if (e.target.matches('.edit-btn')) editRow(row.dataset.id); }).
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Event Delegation: Real-World Examples
todoList.addEventListener('click', e => { if (e.target.matches('.delete-btn')) e.target.closest('li').remove(); if (e.target.matches('.toggle-btn')) e.target.closest('li').classList.toggle('done'); }). One listener handles delete and toggle for all items.
cart.addEventListener('click', e => { if (e.target.matches('.increase')) updateQty(e.target.dataset.id, 1); if (e.target.matches('.decrease')) updateQty(e.target.dataset.id, -1); if (e.target.matches('.remove')) removeItem(e.target.dataset.id); }).
tabs.addEventListener('click', e => { if (e.target.matches('.tab')) switchTab(e.target.dataset.tab); }). One listener on the tab container handles all tab clicks. Check e.target.matches('.tab') and use dataset.tab to identify which tab.
Still have questions?
Browse all our FAQs or reach out to our support team
