How to check if an element is hidden with
JavaScript

How to check if an element is hidden with JavaScript

Photo by Kai Oberhäuser

If you want to check if an element is actually hidden then you can’t just access its ​style ​property with JavaScript (as the properties on the object will be empty unless you have already assigned a value with JavaScript).

You can however use the ​getComputedStyle ​function available on the window object.

window​.​getComputedStyle​(​myElement​).​display ​===​ ​'none'​;
window​.​getComputedStyle​(​myElement​).​visibility ​=== 'hidden'​;

You pass in a reference to the element you are checking and it’s probably worth checking the value of both the display and visibility properties.

You could combine this into a function to check both at the same time.

const​ ​isElementHidden​ ​=​ elem ​=> window​.​getComputedStyle​(​elem​).​display ​===​ ​'none'​ ​|| window​.​getComputedStyle​(​myElement​).​visibility ​===
'hidden'​;

Watch the tutorial for more details.

Follow me on Twitter (@codebubb) for more tutorials!