Please help me. I want to call css property which is located in css file, but I get empty value.
<style>
#a {padding:10px;}
</style>
<div id="a"></div>
<div id="b" style="padding:10px;"></div>
<script>
alert(document.getElementById('a').style.padding);//''
alert(document.getElementById('b').style.padding);//'10px'
</script>
jsfiddle.net
You can't get the shorthand property this way, but you could use this:
alert(window.getComputedStyle(document.getElementById("a"), null).getPropertyValue("padding-top"));
Updated jsFiddle
Edit to add the links from BYossarians comment:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style
Summary:
Returns an object that represents the element's style attribute.
https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle
Summary:
getComputedStyle() gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
This is because without explicitly specifying it is not 'defined' in DOM and being empty and document.getElementById is reading from DOM.
You can try with jQuery which handles all this correctly.
<div id="a"></div>
<div id="b" style="padding:10px;"></div>
<script>
alert($('#a').css('padding'));//''
alert($('#b').css('padding'));//'10px'
</script>
Here is the JS Fiddle
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