Change the class of the Button element to show / hide it.

I am trying to show or hide a button element based on certain criteria in my code. I made a default css button to โ€œhideโ€ it with display: none, and then add a class that changes the display to display: block.

HTML:

<div>
  <button id="show">SHOW</button>
</div>

CSS

#show {
  display: none;
}

#show .visible {
  display: block;
}

JS:

var d = document.getElementById('show');
d.className += "visible";

I also tried:

var d = document.getElementById('show');
d.classList.add("visible");

As well as:

documnet.getElementById('show').classList.add('visible');

The problem is that I cannot force the class to be applied correctly and will not display the button when the class is updated. I am sure that I am missing something simple, just not sure what it is if someone can help.

+4
source share
4 answers

"" , "show".

, CSS #show .visible.

HTML

<div>
  <button id="show">SHOW</button>
</div> 

CSS

    #show {
  display: none;
}

#show.visible {
  display: block;
}

JS

var d = document.getElementById('show');
d.classList.add("visible");
+3

, !

hide , !

function myFunction() {
    var element = document.getElementById("show");
    element.classList.toggle("hide");
}
.hide{
  display:none;
}

#show{
  display: block;
}
<div>
  <button id="show">SHOW</button>
</div>
<button onClick="myFunction()">Toggle</button>
Hide result
+2

. :

#show.visible {
  display: block;
}

:

#show .visible {
  display: block;
}

( #show .visible)

+2

document.getElementById('show').classList.add('visible');
#show {
  /*display: none;*/
}
.invisible{
  display: none;
}
.visible {
  display: block;
}
<div>
  <button id="show" class="invisible">SHOW</button>
</div>
Hide result

2 . .visible, .invisible.

display:none .invisible. #show.

0

Source: https://habr.com/ru/post/1685709/


All Articles