Jessica Jessica - 3 months ago 14
CSS Question

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>




Answer

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

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