Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing style.display property via JS only works when set inline?

Tags:

javascript

css

I'm trying to grab the DISPLAY property of a div on a page. I can only seem to grab it if it was set via an inline style attribute.

If my JS is this:

alert(document.getElementById('myDiv').style.display);

It will alert 'block' with this HTML:

<div id="myDiv" style="display: block;"></div>

However, if I set it via an external style sheet:

#myID {display: block}

and my HTML:

<div id="myDiv"></div>

then my alert is an empty string.

Why is this?

like image 919
DA. Avatar asked Feb 22 '11 20:02

DA.


1 Answers

This is a "feature" of CSS. To actually get the style, you need to use window.getComputedStyle (most browsers) or element.currentStyle (Internet Explorer).

A fix to implement window.getComputedStyle IE can be found at: http://snipplr.com/view/13523/getcomputedstyle-for-ie/. Additionally, see this page for more info: http://www.quirksmode.org/dom/getstyles.html#link7 (there is a script near the bottom for a cross-browser getComputedStyle alternative).

This should work in all browsers (based on function from QuirksMode link above):

var elem = document.getElementById("myDiv");
if (elem.currentStyle) {
    var displayStyle = elem.currentStyle.display;
} else if (window.getComputedStyle) {
    var displayStyle = window.getComputedStyle(elem, null).getPropertyValue("display");
}
alert(displayStyle);
like image 165
jhartz Avatar answered Oct 09 '22 15:10

jhartz