Change class css dynamically in javascript

1

I want to change the value of a property of a css class dynamically with javaScript

For example, having:

$(".miClase").css("visibility", "visible");
.miClase {
  visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="miClase">hola</p>
    
asked by Popularfan 17.12.2018 в 17:23
source

3 answers

2

You could try using:

var elems = document.getElementsByClassName('miClase');
for(var i = 0; i < elems.length; i++)
{
    elems[i].style.visibility = "visible";
}
    
answered by 17.12.2018 / 17:30
source
2

To change styles , which is what you are looking for, it is as follows:

document.getElementById(id).style.property = new style

Example

document.getElementById("idElemento").style.visibility= "visible";

Example in your case:

document.getElementsByClassName("miClase").style.visibility= "visible";
    
answered by 17.12.2018 в 17:33
1

In the case where you want to change the visibility of the first element whose class is miClase you can choose one of these solutions:

  • document.querySelector(".miClase").style.visibility = "visible";
  • document.querySelectorAll(".miClase")[0].style.visibility = "visible";
  • getElementsByClassName('miClase')[0].style.visibility = "visible";
  • If on the other hand you want to change the visibility of all the elements whose class is miClase you can do what you suggested @ GermánMartínez or you can use it in the same way querySelectorAll

        
    answered by 17.12.2018 в 18:35