Jessica
Jessica

Reputation: 9830

CSS style outputting empty string in JavaScript

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>

Upvotes: 0

Views: 1501

Answers (3)

Max Leizerovich
Max Leizerovich

Reputation: 1713

try this:

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

https://jsfiddle.net/uybv41ry/

Upvotes: 0

maciejmatu
maciejmatu

Reputation: 622

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") )

Upvotes: 0

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

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

el = document.getElementById('textWrapper')
style = window.getComputedStyle(el)
padding = style.getPropertyValue('padding')

Upvotes: 2

Related Questions