How do you handle delete buttons in a dynamic list with event delegation?
Add one listener on the list: list.addEventListener('click', e => { if (e.target.matches('.delete-btn')) e.target.closest('li').remove(); }). New items with delete buttons work automatically without adding new listeners.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Event Delegation Implementation Examples
Add one listener on the ul: ul.addEventListener('click', e => { if (e.target.matches('.list-item')) handle(e.target); }). Check e.target to determine which item was clicked. Works for dynamic items.
When the click is on a child (like a button inside a row), use e.target.closest('tr') to find the relevant parent: const row = e.target.closest('tr'); if (row) handle(row). This finds the nearest ancestor matching the selector.
closest() finds the nearest ancestor (including the element itself) that matches a CSS selector. For example, e.target.closest('.menu-item') finds the menu item even if the click was on a child element inside the menu item.
Still have questions?
Browse all our FAQs or reach out to our support team
