Javascript Reference - HTML DOM Style visibility Property








We can use the visibility property in CSS to show or hide an element.

The visibility property in Javascript sets or gets an element visiblity.

Browser Support

visibility Yes Yes Yes Yes Yes

Syntax

Return the visibility property:

object.style.visibility 

Set the visibility property:

object.style.visibility=visible|hidden|collapse|initial|inherit




Property Values

Value Description
visible Show element. This is default
hidden Hide element, but still affects layout
collapse When used with a table, the element is hidden
initial Set to default value
inherit Inherit from parent element.

Technical Details

Default Value: visible
Return Value: A string representing visibility
CSS Version CSS2




Example

The following code shows how to hide a <p> element.


<!DOCTYPE html>
<html>
<body>
<!--   ww  w  .j a  v a2  s.c  o m-->
<p id="myP">This is a p element.</p>

<button type="button" onclick="myFunction()">test</button>

<script>
function myFunction() {
    document.getElementById("myP").style.visibility = "hidden";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 2

The following code shows how to use the display property and the visibility property.


<!DOCTYPE html>
<html>
<body>
<p id="myP1">This is some text.</p>
<p id="myP2">This is some text.</p>
<!--from   w  w  w  .  ja va2  s .c  o m-->
<input type="button" onclick="demoDisplay()" value="display">
<input type="button" onclick="demoVisibility()" value="visibility">
<script>
function demoDisplay() {
    document.getElementById("myP1").style.display = "none";
}

function demoVisibility() {
    document.getElementById("myP2").style.visibility = "hidden";
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to hide and show an <img> element:


<!DOCTYPE html>
<html>
<body>
<!--from   w w  w .  j  a v  a2 s. c  o  m-->
<img id="myImg" src="http://java2s.com/style/demo/border.png" width="100" height="132">
<button type="button" onclick="hideElem()">Hide image</button>
<button type="button" onclick="showElem()">Show image</button>
<script>
function hideElem() {
    document.getElementById("myImg").style.visibility = "hidden"; 
}

function showElem() {
    document.getElementById("myImg").style.visibility = "visible"; 
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to get the visibility type.


<!DOCTYPE html>
<html>
<body>
<p id="myP" style="visibility:hidden;">This is a p element.</p>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--   www .  j a  v a2s  .c  o m-->
    console.log(document.getElementById("myP").style.visibility);
}
</script>

</body>
</html>

The code above is rendered as follows: