Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call css property [for ex.: element.style.padding]

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

like image 606
user3073240 Avatar asked Dec 01 '25 20:12

user3073240


2 Answers

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.

like image 89
rusmus Avatar answered Dec 03 '25 11:12

rusmus


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

like image 39
KoalaBear Avatar answered Dec 03 '25 10:12

KoalaBear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!