How to hide/show HTML elements in JavaScript?


Using Css style we can hide or show HTML elements in javascript. Css provides properties such as block and none to hide/show the HTML elements.

Hiding an element

Example

In the following example when the "Hideme" button has clicked the text in the paragraph tag has been disappeared as shown in the output.

Live Demo

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

Once the above code is executed, the following will be displayed

From the above block, If we click on the "Hideme" button, the text present in the block will be disappeared as shown in the output, leaving only the button.

Output

Showing an element

Example

In the following example, the text in the paragraph tag is initially hidden but when the "Showme" is clicked the text has appeared as shown in the output.

Live Demo

<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="ShowMe">
</body>
</html>

Once the above code is executed, the following will be displayed on the screen

If we click the above button the following output will be executed

Output


Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements