4

I tested the visibility of the following div:

<div id="div1">div</div>

with the style defined separately

#div1 {
    visibility:visible; //or hidden
}

If the style is defined inline as <div id="div1" style="visibility:visible">div</div> there it's easy to check the visibility in the element.style.visibility property. But the problem is when the style is defined separately (as shown above - #div1, .div1 or div).

And so where can one check the visibility property using only pure javascript? jQuery returns correct style everytime (I dunno how to track it), so how did they do it? Here is one fiddle with my unsuccesful attempts, no tests except jQuery's work:

alert($(el).css('visibility')); // jQuery works well - returns correct property
alert(el.style.visibility); // not works - always empty string
alert(el.offsetWidth > 0 || el.offsetHeight > 0 ? 'yes':'no'); // also not working - always true - http://stackoverflow.com/questions/1343237/how-to-check-elements-visibility-via-javascript
alert(el.getComputedStyle); // undefined - http://stackoverflow.com/questions/4795473/check-visibility-of-an-object-with-javascript
alert(el.getAttribute('visibility')); // not works - of course null

Any ideas on how to succeed? Tested in latest Firefox 15.

Stano
  • 8,749
  • 6
  • 30
  • 44

3 Answers3

6

getComputedStyle is a global method. Use it as follows:

window.getComputedStyle(el, null).getPropertyValue('visibility');
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • I have an Android project with a `webview` showing an HTML + Javascript, and this give me an error: `"Uncaught TypeError: Cannot call method 'getPropertyValue' of null"`. I guess it does not understand what a `window` is? – Luis A. Florit Feb 17 '16 at 23:09
3

You are using getComputedStyle wrong:

getComputedStyle( el ).visibility
//"visible"

Demo: http://jsfiddle.net/hMFry/1/

In internet explorer you would use:

el.currentStyle.visibility;
Esailija
  • 138,174
  • 23
  • 272
  • 326
2
getComputedStyle(el).getPropertyValue('visibility');
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79