Solo puedo acceder al primer elemento en h1. También puedo crear un botón y hacer clic en un bucle a través de los elementos h1 y activar o desactivar la clase .textDecoration. Pero mi objetivo es hacer clic en el elemento que quiero paso a paso y activar o desactivar la clase .textDecoration.
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>te sugiero que delegues
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>Tu pregunta me parece muy mal formulada, ¿buscas eso?
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>