Tutorials using JS
Problem Statement
check if an element is hidden in the document using JavaScript
Solution
an element can be hidden using hidden
attribute in the html or display:none
in CSS. we can get the computed style of this element using getComputedStyle().display
property
window.getComputedStyle(element).display
to check if the element is hidden, compare the value returned by the above property with the value "none"
, as shown in the following boolean expression
window.getComputedStyle(element).display === "none"
this expression returns true
if the element is hidden, or false
otherwise
Program
in the following program, we check if the paragraph with id "myPara"
is hidden or not
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Check if div is hidden</h2>
<button id="myBtn">Click me</button><br>
<div id="myDiv" hidden>A Div</div>
<p id="output"></p>
<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
let myDiv = document.getElementById("myDiv");
if(window.getComputedStyle(myDiv).display === "none") {
document.getElementById("output").innerHTML = 'the div element is hidden';
} else {
document.getElementById("output").innerHTML = 'the div element is not hidden';
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Check if div is hidden</h2>
<button id="myBtn">Click me</button><br>
<div id="myDiv">A Div</div>
<p id="output"></p>
<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
let myDiv = document.getElementById("myDiv");
if(window.getComputedStyle(myDiv).display === "none") {
document.getElementById("output").innerHTML = 'the div element is hidden';
} else {
document.getElementById("output").innerHTML = 'the div element is not hidden';
}
});
</script>
</body>
</html>