Event delegation

One listener on a parent handles clicks for current and future children.

javascript intermediate #dom#events#performance
プレイグラウンドで開く
js-event-delegation.js
document.body.innerHTML = `
  <ul id="todo">
    <li>Write tests <button data-action="done">Done</button></li>
    <li>Deploy <button data-action="done">Done</button></li>
  </ul>`;

document.getElementById("todo").addEventListener("click", (event) => {
  const button = event.target.closest("[data-action='done']");
  if (!button) return;
  const item = button.closest("li");
  item.style.textDecoration = "line-through";
  console.log("finished:", item.firstChild.textContent.trim());
});

document.querySelector("[data-action='done']").click();