0

Something weird is going on and I'm not sure what it is. I created a bunch of elements and I want to get the width of my progress bar so I can work with it in my JS code.

In my JS I do:

var bar = document.getElementById('progressBar');
console.log(bar.style.width); //empty string

however in my CSS I have

#progressBar{
  width: 600px;
  border: 2px solid black;
}

and I can clearly see the 600px container and the border around it in the browser, but for some reason, JS doens't know about these CSS settings.

Any ideas what the problem might be?

EDIT: This is different from the suggested duplicate - the problem is not that I don't know how to the get the value, the problem is that the style.value doesn't get me what I expect.

ribarcheto94
  • 436
  • 11
  • 25

1 Answers1

1

That is correct behaviour.

The style property of a DOMElement is responsible for inline styles, not the actual computed values. To get the width, use getClientRects or getBoundingClientRect.

e.g.

var bar = document.querySelector('.bar');
console.log(bar.style.width); // empty string
console.log(bar.getBoundingClientRect().width); // 100px
.bar {
  width: 100px;
  height: 20px;
  background: blue;
}
<div class='bar'></div>

You may also be interested in: How do I get a computed style?

Community
  • 1
  • 1
noahnu
  • 3,479
  • 2
  • 18
  • 40
  • Thanks! I didn't know that this was only for `inline` styles. I've worked with `style.attribute` before and it seemed to do the job even when I was working with external CSS files. There's always random stuff like this when doing web dev. How is one supposed to know about this? – ribarcheto94 May 17 '17 at 22:23
  • Actually, this is also not entirely accurate. It gives you the width including padding and border. I want something that gives me just the specified width. The suggested link for getting a computed style gets me what I want but it's a string (like "100px") but I need the actual number 100. A combination of these 2 would be ideal. – ribarcheto94 May 17 '17 at 22:39
  • parseInt(window.getComputedStyle(bar).getPropertyValue('width')); did the trick! Thanks for pointing me in the right direction! – ribarcheto94 May 17 '17 at 22:45