0

I'm trying to get the padding value of an element in JavaScript. Here's how:

var textWrapper = document.getElementById('textWrapper');
console.log(textWrapper.children[0].style.padding);

It outputs an empty string, even though in the css style, the padding is set to 10px. What am I doing wrong, and how can I fix it?

JSFiddle

console.clear()

var textWrapper = document.getElementById('textWrapper');
console.log(textWrapper.children[0].style.padding);
.text {
  width: 200px;
  height: 50px;
  padding: 10px;
}
<div id="textWrapper">
  <div class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do</div>
  <div class="text">Duis aute irure dolor in reprehenderit</div>
  <div class="text">Excepteur sint occaecat cupidatat non</div>
  <div class="text">"Sed ut perspiciatis unde omnis iste natus error sit</div>
</div>
Jessica
  • 9,379
  • 14
  • 65
  • 136
  • Element.style is the actual HTML style added to an element, not the css class. "
    " that would return 25px with your code.
    – user2267175 Aug 28 '16 at 22:38
  • Possible duplicate of [Get a CSS value with JavaScript](http://stackoverflow.com/questions/6338217/get-a-css-value-with-javascript) – JJJ Aug 28 '16 at 22:49

3 Answers3

2

.style property gets inline CSS. Use getComputedStyle() instead.

el = document.getElementById('textWrapper')
style = window.getComputedStyle(el)
padding = style.getPropertyValue('padding')
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
0

I found that this works

window.getComputedStyle(textWrapper.children[0], null).getPropertyValue('padding')

Although it returns string with pixels (e.g. "10px"), not just a number.

To get pure number use parseInt() on the output (like that : parseInt("10px") )

maciejmatu
  • 572
  • 1
  • 8
  • 14
0

try this:

console.clear()
var textWrapper = document.getElementById('textWrapper');
console.log(window.getComputedStyle(textWrapper.children[0]).padding);

https://jsfiddle.net/uybv41ry/

Max Leizerovich
  • 1,536
  • 1
  • 10
  • 7