How can I handle clicks on items added to a list later?
Quick answer
The question, the details, the next step.
A practical checklist
Attach the listener to a parent that remains in the page.
Use a selector that identifies the intended item, including when the click lands on a nested child.
Check that a matching item exists and is contained by the delegated parent.
Add new items inside that parent; the same listener can handle their clicks.
If the handler does not run, check whether propagation is stopped before the event reaches the parent.
A few more useful answers
Do I need to attach another listener whenever I add an item?
Not with this pattern. The parent listener handles bubbling clicks from items added inside it, so you can add items without attaching a click listener to each one. [S1]
What if the clicked item contains an icon or button?
Use closest() to find the matching item above the click target, then check that the match belongs to the intended parent. [S2]
Can this handle a click that does not reach the parent?
No. Delegation relies on the event reaching the parent; stopping propagation can prevent the delegated handler from receiving it. [S1]
Sources
References used for this guide.
- [S1] Event bubbling — Learn web development | MDN developer.mozilla.org · Checked
- [S2] Selection and traversal on the DOM tree — Web APIs | MDN developer.mozilla.org · Checked
