In this post, we will learn how to check if an element is hidden or visible with JavaScript. If an element is hidden in a document, it becomes a bit difficult to find. But it is easy to find the hidden element with the help of JavaScript. So how we can find hidden element or check the element, it is hidden or visible with JavaScript, we will learn in this post. 


How To Check If An Element Is Hidden or Visible With JavaScript ?


Check If An Element Is Hidden or Visible

To check if an element is hidden or visible, we use getComputedStyle() method to check element is hidden or not. 


If an element is hidden with display:none CSS property then we will find it as following example:


<!DOCTYPE html>
<html>
<head>
<title>How To Check If An Element Is Hidden or Visible With JavaScript ?</title>
<style>

#hiddenDIV {
width: 100%;
padding: 30px 0;
text-align: center;
background-color: #f2f2f2;
margin-top: 20px;
display: none;
}

</style>
</head>
<body>

<div id="hiddenDIV">
This is Hidden DIV.
</div>

<button onclick="findHiddenDIV()">Find DIV</button>


<script>

function findHiddenDIV() {
var div = document.getElementById("hiddenDIV");


//Check div is hidden or not. If hidden then display
if (window.getComputedStyle(div).display === "none") {
div.style.display = "block";
}
}

</script>
</body>
</html> code-box

If an element is hidden with visibility:hidden CSS property then we will find it as following example:


<!DOCTYPE html>
<html>
<head>
<title>How To Check If An Element Is Hidden or Visible With JavaScript ?</title>
<style>

#hiddenDIV {
width: 100%;
padding: 30px 0;
text-align: center;
background-color: #f2f2f2;
margin-top: 20px;
display: none;
}

</style>
</head>
<body>

<div id="hiddenDIV">
This is Hidden DIV.
</div>

<button onclick="findHiddenDIV()">Find DIV</button>


<script>

function findHiddenDIV() {
var div = document.getElementById("hiddenDIV");


//Check div is hidden or not. If hidden then display
if (window.getComputedStyle(div).visibility === "hidden") {
div.style.visibility = "visible";
}
}

</script>
</body>
</html> code-box


Summary

In this post we learned how to check if an element is hidden or visible with JavaScript. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post