Home > front end >  I want to toggle .textDecoration class when I am clicking on "ALL" h1 elements. Can you He
I want to toggle .textDecoration class when I am clicking on "ALL" h1 elements. Can you He

Time:01-08

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>

CodePudding user response:

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>

CodePudding user response:

Your question seems to me very poorly formulated, are you looking for that?

document.querySelectorAll('h1').forEach( (Hn,_,All_h1) =>
  {
  Hn.onclick =_=>
    {
    if (Hn.classList.toggle('textDecoration'))
      All_h1.forEach( Hx=> Hx.classList.toggle('textDecoration', Hn===Hx) )
    }  
  })
.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>

  •  Tags:  
  • Related