javascripthtmlcsstogglegetelementsbytagname

I want to toggle .textDecoration class when I am clicking on "ALL" h1 elements. Can you Help me with this Code?


I can only access the first element in h1. I also can create a button and click loop through h1 elements and switch on or off .textDecoration class. But my aim is to click which element I want step by one and switch on or off .textDecoration class.

var x = document.getElementsByTagName("h1")[0];

function myFunction() {

  x.classList.toggle("textDecoration");
}

x.addEventListener("click", myFunction);
.textDecoration {
  text-decoration: line-through;
}
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>


Solution

  • I suggest you delegate

    document.getElementById("container").addEventListener("click", function(e) {
      const tgt = e.target.closest("h1");
      if (tgt) tgt.classList.toggle("textDecoration");
    })
    .textDecoration {
      text-decoration: line-through;
    }
    <div id="container">
      <h1>Text-Decoration: line-through</h1>
      <h1>Text-Decoration: line-through</h1>
      <h1>Text-Decoration: line-through</h1>
      <h1>Text-Decoration: line-through</h1>
    </div>