Delegation Closest Lab
Nested icon clicks break bare event.target; closest recovers the control.
Same buttons, two handlers
Each button nests a <span class="icon">. Click the star — not the button chrome — and compare the readouts.
Fragile: bare event.target
Click a star or label.
Robust: closest("[data-id]")
Click a star or label.
Tabs and similar widgets need roles such as role="tablist", role="tab", and
aria-selected (as in a draft-desk pattern) — not bare click handlers alone.
Important HTML
The actionable element owns data-id; the icon is a nested child.
<button type="button" data-id="shoot">
<span class="icon" aria-hidden="true">★</span> Shoot
</button>
Important JavaScript
Prefer closest so a click on the icon still finds the button.
// Fragile — fails when target is the span
board.addEventListener("click", function (event) {
const id = event.target.dataset.id;
});
// Robust — walks up to the control
board.addEventListener("click", function (event) {
const btn = event.target.closest("[data-id]");
if (!btn) return;
const id = btn.dataset.id;
});