Hide or show HTML elements using visibility property in JavaScript

The visibility property is used to hide or show the content of HTML elements. The visibility property specifies that the element is currently visible on the page. The ‘hidden’ value can be used to hide the element. This hides the element but does not remove the space taken by the element, unlike the display property.

Syntax:

element.style.visibility = 'hidden';
element.style.visibility = 'visible';

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        Hide or show HTML elements using
        visibility property in JavaScript
    </title>
      
    <style>
            .container {
            height: 80px;
            width: 250px;
            border: 2px solid black;
            background-color: green;
            color: white;
    </style>
</head>
  
<body>
    <center>
        <div class="container">
            <h1>GeeksforGeeks</h1>
        </div>
          
        <p>
            Click the buttons to show
            or hide the green box
        </p>
  
        <button onclick="showElement()">
            Show Element
        </button>
          
        <button onclick="hideElement()">
            Hide Element
        </button>
    </center>
      
    <script type="text/javascript">
        function showElement() {
            element = document.querySelector('.container');
            element.style.visibility = 'visible';
        }
  
        function hideElement() {
            element = document.querySelector('.container');
            element.style.visibility = 'hidden';
        }
    </script>
</body>
  
</html>                    

chevron_right


Output:

  • Clicking the Hide button:
    visibility-hide
  • Note: Here after clicking the hide button the element will become invisible and left the space blank.

  • Clicking the Show button:
    visibility-show


My Personal Notes arrow_drop_up

Technical Writer Lets have an update

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.