Here is my problem : the css style is not initialised when window.onload is triggered.
<div id="foo"></div>
css file
#foo {
height: 200px
}
js file
window.onload = function(){
console.log(document.getElementById('foo').style.height);
};
the console displays : ""
the style must be in a different file, if the style attribute is used (style="height=200px") it works.
.style.height
does not show styles that come from CSS rules. It only returns styles that have been explicitly set on that object, either in the HTML or via javascript, not styles inherited from CSS rules.
Instead, you must use window.getComputedStyle()
. See the MDN doc for more details on how to use getComputedStyle()
properly. Here's one example:
window.getComputedStyle(document.getElementById('foo'),null).getPropertyValue("height");
Note: for older versions of IE, you have to either install a polyfill for getComputedStyle
or use el.currentStyle
.
Element.style will only be set for inline styles(<div id="foo" style="height: 200px"></div>
), to get the computed style use window.getComputedStyle
window.getComputedStyle(document.getElementById("foo"), null).getPropertyValue('height')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With