linked to another question, I ran into the following problem.
I have several elements (in my case, images) with the same class (say "image1"). Using a button, I want to toggle (add and remove) a class (hiding and showing the pictures).
I use document.getElementsByClass("image1")
to get those elements (images). Now I need to toggle the class - unfortunately, I can’t get it to.
My first instinct (coming from getElementById) was
var elementImg = document.getElementsByClass("image1");
elementImg.classList.toggle("hiddenclass");
…where hiddenclass contains the single line display:none;
(and for the fun of it I also tried const instead of var).
But (to little surprise) it does not work, as getElementsByClass returns not a single element, but a HTMLCollection.
And no matter how I search the web, I can not find a solution and a hint that eventually works.
Maybe someone among you already encountered this problem and can provide a solution.
Thanks in advance!
P.S. Apparently jQuery has the method .toggleClass(), but I have little to no notion of jQuery, and it does not seem to solve the problem to access multiple elements with the same class.
Using the solution from here, here's the answer to the above mentioned problem:
Array.from(document.getElementsByClassName("image1"))
.forEach((element) => element.classList.toggle("hiddenspan"));
…and it worked like charm.