How to Check if an Element is Visible or Hidden with JavaScript

In this tutorial, we will learn how to check if an HTML element is visible or hidden using pure JavaScript and jQuery.

 

All of the methods below work for both inline styling and styling applied VIA a separate style sheet.

 

JavaScript offsetParent Property

The cleanest way to check if an element is hidden is to use the JavaScript offsetParent property. If the element is hidden its offsetParent value will be null.

 

#thing {
  display: none;
}
<div id="thing">A Test Element</div>

 

let thing = document.getElementById('thing');

if (thing.offsetParent === null) {

  console.log("Element is hidden.");

} else {

  console.log("Element is visible.");
}

 

JavaScript getComputedStyle() Method

Another way to check if an element is hidden is to use the window.getComputedStyle() method. It will return the display property value of the object. We can check if the string is equal to none meaning the element is hidden and do something.

 

#thing {
  display: none;
}
<div id="thing">A Test Element</div>
let thing = document.getElementById('thing');

if (window.getComputedStyle(thing).display == 'none') {

  console.log("Element is hidden.");

} else {

  console.log("Element is visible.");
}

 

Check if Element is Visible with jQuery

Use the jQuery :visible selector to check if an element is visible like this:

 

if($("#thing").is(":visible")){
   console.log("Element is visible.");
} else{
   console.log("Element is hidden.");
}

 

 

Check if Element is Hidden with jQuery

Use the jQuery :hidden selector to check if an element is hidden like this:

 

if($("#thing").is(":hidden")){
   console.log("Element is hidden.");
} else{
   console.log("Element is visible.");
}

 

Conclusion

You now know four different ways of check if an element is hidden using JavaScript and jQuery.