How can I use JavaScript to toggle between classes? I can't seem to understand why an element that is set to display: none;
is unable to receive a class using classList.
In simpler terms, if I define
#div1{
width: 25%;
background-color: #000000;
display: none;
}
#div2{
width: 50%;
height: 10px;
background-color: #cccccc;
}
.fullview{
width: 99%;
height: 500px;
border-radius: 5px;
border: 1px solid #000000;
}
and use the following HTML:
<div id="div1">
content here
</div>
<div onclick="myFunction()" id="div2">
content here
</div>
<script>
function myFunction() {
document.getElementById("div1").classList.toggle("fullview");
}
</script>
the div1
does not receive the fullview
class.
However, if I remove display: none;
from div1
and apply it to the fullview
class instead, the script works fine. But I do not want div1
to be visible or to reserve space until div2
is clicked.
Is this because the script runs before the div is "created"?
What are my alternatives in this scenario?