How to check element's visibility via javascript?

You are looking for one solution to two different scenarios.

The first scenario is getting the cascaded/computed style for a css property. See this answer for how to do that.

The second scenario is detecting if any of an element's parents are hidden. This requires traversing and is cumbersome and slow.

You can take the solution outlined here (and employed by jQuery/Sizzle since 1.3.2), and just read the dimensions of the element:

var isVisible = element.offsetWidth > 0 || element.offsetHeight > 0;

If it has dimensions then it is visible in the sense that it takes up some rectangular space (however small) in the document. Note that this technique still has some downsides for certain elements in certain browsers, but should work in most cases.


This is the quickest and easiest way to determine if an element is visible.

function is_visible(e) {return e.offsetWidth > 0 || e.offsetHeight > 0;}

Each case will need its own check and you need to know the ID of that element. First, grab the element (just doing this to make the code readable):

var MyElementName = document.getElementById("MyElementName");

Then do your checks:

Case 1:

 if (MyElementName.style.display == "none")

Case 2, looking at the parent, checking FF first:

if ((MyElementName.previousSibling.nodeType == 3 )
    && (MyElementName.parentNode.nextSibling.style.display == "none"))

then for other browsers:

else (MyElementName.parentNode.style.display == "none")

Case 3, look for an applied css class:

if (MyElementName.className = "SomeClass")

Tags:

Javascript

Css