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?
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?
Share Improve this question asked Feb 22, 2011 at 20:56 DA.DA. 40.7k51 gold badges158 silver badges217 bronze badges 1- Are you running your javascript before loading your HTML? – Ryan Kinal Commented Feb 22, 2011 at 21:23
1 Answer
Reset to default 13This 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./view/13523/getputedstyle-for-ie/. Additionally, see this page for more info: http://www.quirksmode/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);