<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to check if element
is visible in DOM?
</
title
>
<
style
>
.visible {
height: 100px;
width: 100px;
background-color: green;
}
.invisible {
height: 100px;
width: 100px;
background-color: green;
display: none;
}
</
style
>
</
head
>
<
body
>
<
h1
style
=
"color: green"
>
GeeksforGeeks
</
h1
>
<
b
>
How to check if element
is visible in DOM?
</
b
>
<
p
>Below is a visible object</
p
>
<
div
class
=
"visible"
></
div
>
<
p
>Below is a invisible object</
p
>
<
div
class
=
"invisible"
></
div
>
<
p
>
Click on the button to check for the
visibility of the objects.
</
p
>
<
p
>
Output for visible object:
<
span
class
=
"outputVisible"
></
span
>
</
p
>
<
p
>
Output for non visible object:
<
span
class
=
"outputInvisible"
></
span
>
</
p
>
<
button
onclick
=
"checkVisibility()"
>
Click here
</
button
>
<
script
type
=
"text/javascript"
>
function isElementVisible(element) {
let style = window.getComputedStyle(element);
if (style.display == 'none')
return false;
else
return true;
}
function checkVisibility() {
visibleObject =
document.querySelector(".visible");
invisibleObject =
document.querySelector(".invisible");
document.querySelector(".outputVisible").textContent
= isElementVisible(visibleObject);
document.querySelector(".outputInvisible").textContent
= isElementVisible(invisibleObject);
}
</
script
>
</
body
>
</
html
>