How to hide/show HTML elements in JavaScript?

JavaScript provides several ways to hide and show HTML elements by manipulating their CSS properties. The most common approach is using the display property with values like none (to hide) and block (to show).

Hiding an Element

To hide an element, set its display property to none. This removes the element from the document flow completely.

Example

In the following example, clicking the "Hide Me" button hides the paragraph text:

<html>
<body>
    <p id="hide">Using JavaScript to hide HTML elements.</p>
    <input type="button" onclick="document.getElementById('hide').style.display='none'" value="Hide Me">
</body>
</html>

Showing an Element

To show a hidden element, set its display property to block, inline, or its original display value.

Example

In this example, the paragraph is initially hidden but becomes visible when the "Show Me" button is clicked:

<html>
<body>
    <p id="show" style="display:none">JavaScript can show hidden HTML elements</p>
    <input type="button" onclick="document.getElementById('show').style.display='block'" value="Show Me">
</body>
</html>

Toggle Visibility

You can create a toggle function to switch between hiding and showing an element:

<html>
<body>
    <p id="toggle">Click the button to toggle my visibility!</p>
    <input type="button" onclick="toggleElement()" value="Toggle">
    
    <script>
    function toggleElement() {
        let element = document.getElementById('toggle');
        if (element.style.display === 'none') {
            element.style.display = 'block';
        } else {
            element.style.display = 'none';
        }
    }
    </script>
</body>
</html>

Alternative Methods

Besides display, you can use other CSS properties:

  • visibility: hidden hides the element but keeps its space
  • opacity: 0 makes the element transparent but still interactive
<html>
<body>
    <p id="visibility-demo">This text uses visibility property</p>
    <p id="opacity-demo">This text uses opacity property</p>
    
    <button onclick="document.getElementById('visibility-demo').style.visibility='hidden'">Hide with Visibility</button>
    <button onclick="document.getElementById('opacity-demo').style.opacity='0'">Hide with Opacity</button>
</body>
</html>

Comparison

Property Hides Element Keeps Space Still Clickable
display: none Yes No No
visibility: hidden Yes Yes No
opacity: 0 Yes Yes Yes

Conclusion

Use display: none for complete hiding, visibility: hidden to preserve layout space, or opacity: 0 for transparent but interactive elements. The choice depends on your specific needs.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements