How to style css with javascript searching for classes

Asked

Viewed 51 times

0

Aim and grab invisible text with css effect visibility: hidden; and through Avascript I want to pass a function that when I press a button all classes with visibility: hidden be visible. I understood?

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;
}

2 answers

3

Let me start by mentioning that getElementsByClassName returns a list of widgets that have the specified class. You must pass only the class name that would be answer and not .answerr as it did, for that would already be a selector.

If you return a list of items then you must use one for to make the modifications in all.

The most direct way to add and remove classes to a pure Javascript element is by using classList. This has the 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 the css classes. The ones you have are very difficult to decipher what they mean and will make it difficult for you in the future when you review the code again.

0

Try this:

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

elementos.forEach(function(x){
  x.classList.add('newclass');
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.