Languages
[Edit]
EN

JavaScript - hide and show element

0 points
Created by:
user4838
728

In this article, we would like to show you how to hide and show elements using CSS display property with JavaScript.

1. By modifying CSS display property

In this example, we create an invisible element with CSS display property set to none. Then we replace the class of the element using replace() method, to set display property to block and make it visible.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    .invisible {
      display: none;
    }

    .visible {
      display: block;
    }
  </style>
</head>
<body>
  <div id="element" className="invisible">Some content here ...</div>
  <script>

    var element = document.querySelector('#element');

    element.classList.replace('invisible', 'visible');

  </script>
</body>
</html>

Note:

The replace() method from the example above is equivalent to remove() and add() operations.

element.classList.replace('invisible', 'visible');

is equivalent to:

element.classList.remove('invisible');
element.classList.add('visible');

2. By modifying CSS visibility property

This example is similar to the first one, but this time, instead of display CSS property, we use visibility. 

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    .invisible {
      visibility: hidden;
    }

    .visible {
      visibility: visible;
    }
  </style>
</head>
<body>
  <div id="element" className="invisible">Some content here ...</div>
  <script>

    var element = document.querySelector('#element');

    element.classList.replace('invisible', 'visible');

  </script>
</body>
</html>

See also

  1. JavaScript - add, remove, get and check element class name

  2. JavaScript - hide and show element on click event

  3. JavaScript - hide and show element using placeholder

References

  1. Element.classList - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join