I begin by mentioning that getElementsByClassName
returns a list of elements that has the specified class. You have to pass only the class name that would be answer
and not .answerr
as you did, since this would already be a selector.
If you return a list of elements then you must use a for
to make the modifications at all.
The most direct way to add and remove classes to a pure Javascript element is by using classList
. This has method add
to add a new class and remove
to remove. Then in your case you can remove the old class and add the new one.
Example:
document.getElementById("ativa").addEventListener("click", function(){
const escondidos = document.getElementsByClassName('answerr'); //sem o .
for (let i = 0; i < escondidos.length; ++i){
escondidos[i].classList.remove("answerr"); //tirar a classe antiga
escondidos[i].classList.add("newclass"); //por a nova
}
});
.answerr {visibility:hidden;}
.newclass{
visibility:visible;
}
<div>div1</div>
<div>div2</div>
<div class="answerr">div3</div>
<div class="answerr">div4</div>
<button id="ativa">Ativa</button>
As a suggestion, give clearer names to both the variables you create in Javascript and to classes in css. The ones you have are pretty hard to decipher what they mean and will make it harder for you in the future when you revisit the code again.