top of page

How to Hide or Show Elements in JavaScript?



In JavaScript, we can hide the elements using the style.display or by using the style.visibility. The visibility property in JavaScript is also used to hide an element. The difference between the style.display and style.visibility is when using visibility: hidden, the tag is not visible, but space is allocated. Using display: none, the tag is also not visible, but there is no space allocated on the page.


In HTML, we can use the hidden attribute to hide the specified element. When the hidden attribute in HTML sets to true, the element is hidden, or when the value is false, the element is visible.


Syntax

The general syntax to hide an element using style.hidden and style.visibility is given as follows.


Using style.hidden

document.getElementById("element").style.display = "none";  

Using style.visibility

document.getElementById("element").style.visibility = "none";  



Hide the Element


Code:

<!DOCTYPE html>
<html>

<body>
   <p>Click the "Hide Me" button to hide the Image:</p>
   <div id = "div" >
      <img src="https://static.wixstatic.com/media/0f65e1_cf4192db4cc54cae8ab1b3087c5af842~mv2.jpg" alt="" width="500 px" height="100 px">
   </div>
   <button onclick="myFunction()">Hide Me</button>
   <script>
   function myFunction() {
   document.getElementById("div").style.display = "none";
   }
   </script>
</body>

</html>

Output:





Show the Element


Code:

<!DOCTYPE html>
<html>

<body>
   <p>Click the "Show me" button to show element the DIV element:</p>
   <div id = "div" >
      <img src="https://static.wixstatic.com/media/0f65e1_cf4192db4cc54cae8ab1b3087c5af842~mv2.jpg" id ="div2" alt="" width="500 px" height="100 px" style="display:none">

   </div>
   <button onclick="myFunction()">Show Me</button>

   <script>
   function myFunction() {

   document.getElementById("div2").style.display = '';
   }
   </script>
</body>

</html> 

</html> 

Output:




The Tech Platform

Recent Posts

See All

Comentários


bottom of page