Why does a parent element react when I click a nested button?
Quick answer
A click on a button inside another element can bubble upward, so handlers on both the button and its parent may run. In a handler, event.target identifies the event’s target; event.currentTarget identifies the element whose listener is running. Log both to see the difference. If the parent should not respond to that click, check its handler’s logic or deliberately stop propagation when appropriate. [S1] [S2]
The question, the details, the next step.
A practical checklist
List the elements with click handlers, including ancestors of the button.
Log
event.targetandevent.currentTargetin each relevant handler.Test clicks on the button text, any nested icon, and the card outside the button.
Decide which clicks should activate the card before changing propagation.
Retest both the button action and the card action after the change.
A few more useful answers
Does `event.target` always equal the element whose handler is running?
No. target identifies the event’s target, while currentTarget identifies the element whose listener is currently being invoked. They can differ when an event bubbles through nested elements. [S2]
Should I always call `stopPropagation()` in the button handler?
No. Use it when you specifically want the event not to continue to ancestor handlers. Otherwise, consider handling the button click in the parent’s logic so other intended bubbling behavior remains.
What if the parent handler runs even though I do not see a parent click listener?
Check the ancestors for handlers attached elsewhere in your code, and log currentTarget in the handler that runs. That identifies the element whose listener is being invoked. [S2]
Sources
References used for this guide.
- [S1] Event bubbling — Learn web development | MDN developer.mozilla.org · Checked
- [S2] Event — Web APIs | MDN developer.mozilla.org · Checked
