How to put css style with javascript looking for classes

0

Goal and get invisible text with css visibility: hidden; e effect through javaScript I want to pass a function that when I push a button all classes with visibility: hidden are visible .. did you understand?

I have the following code

function ativa (){

// buscando as classes com efeito hidden

    var x = document.getElementsByClassName('.answerr');

//botando o novo efeito para quando eu apertar o button* a class apareça

    var newclass = document.createAtributte('class' 'newclass');

    x.setAttribute(newclass);
}

css

.answerr {visibility:hidden;}

//novo estilo que quero adicinar

.newclass{
     visibility:visible;
}
    
asked by anonymous 11.08.2018 / 20:25

2 answers

3

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.

    
11.08.2018 / 20:49
0

Try this:

var elementos = document.querySelectorAll('.answerr');

elementos.forEach(function(x){
  x.classList.add('newclass');
});
    
11.08.2018 / 20:42