Facebook Pixel

What is e.target.closest() in event delegation?

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.

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.

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.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.