skip to Main Content

I have a HTML UL element that I want to hide with the .hidden property dynamically with JavaScript. Problem is, when there is a CSS rule: display: block on the element, the hidden property does not work.

document.getElementById('myid').hidden = true;
#myid {
  display: block;
}
<div id="myid">Lorem ipsum</div>

The browser adds the hidden property to the element correctly, but the element does not hide because display: block is set.

I expected that JavaScript will override the CSS. What use is then to have the hidden property?
Why is this? and is this a bug?

2

Answers


  1. You need a CSS rule [hidden] {display:none!important;}. Something like this.

    function toggle(){
    var elem=document.getElementById('myid');
    elem.hidden = !elem.hidden;
    }
    #myid {
      display: block;
    }
    [hidden]{
    display:none!important;
    }
    <div id="myid">Lorem ipsum</div>
    <button type="button" onclick="toggle()">Toggle</button>
    Login or Signup to reply.
  2. You can toggle CSS classes:

    function toggle(){
      const div = document.getElementById('myid');
      div.classList.toggle("is-shown");
      div.classList.toggle("is-hidden");
    }
    

    CSS classes:

    .is-hidden {
        display: none !important;
    }
    
    .is-shown {
        display: block !important;
    }
    

    HTML:

    <div id="myid" class="is-shown">Lorem ipsum</div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search