Change CSS display to none or block using pure JavaScript

← Prev

I have previously shared an article showing how to change CSS display property to none or block using jQuery. It is also possible using plain old JavaScript. You can use the style display property (a one line solution) in JavaScript to change CSS display to either none or block dynamically.

Change CSS display to "none"

Let us assume, I have DIV element whose "display" property is set to "block" (visible). block or inline, is the default display value. I want to make the element invisible.

You can write an inline script or you can call a function.

Here's an "inline" script to set the display property of an element to "none".

<style>
    div {
      display: block;
    }
</style>

<body>
  <div id='div'>Some content here inside DIV...</div>

  <p>
    <input type='button' value='Click to hide DIV' id='bt' 
           onclick='document.getElementById("div").style.display = "none";' />
  </p>
</body>
Try it

I have highlighted the ".style.display" property.

Change CSS display to "block"

Now, lets assume, the display property to set to "none" (invisible). You can simply set the "style.display" property to "block" like this.

<style>
    div {
      display: none;
    }
</style>

<body>
  <div id='div'>Some content here inside DIV...</div>

  <p>
    <input type='button' value='Click to hide DIV' id='bt' 
           onclick='document.getElementById("div").style.display = "block";' />
  </p>
</body>

Toggle display property of element using JavaScript

You can easily toggle the display property of an element using a simple JS method.

<!DOCTYPE html>
<html>
<body>
  <h2>Click button to toggle display of the DIV element.</h2>

  <div id='div' style='display: block;' 
    Some content here inside DIV...
  </div>

  <p>
    <input type='button' value='Show/Hide element' id='bt' 
           onclick='toggle()' />
  </p>
</body>
<script>
    let toggle = () => {
      const el = document.getElementById("div");

      // using ternary operator to toggle display property of the element.
      el.style.display === 'none' ?
        el.style.display = 'block' : el.style.display = 'none';
    };
</script>
</html>
Try it

Ternary Operator is used in the above example, to check the "display" property of the element and accordingly change the value.

← Previous