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.

2
  • try to paste ur code in codepen Commented May 17, 2017 at 22:01
  • Possible duplicate of Get a CSS value with JavaScript Commented May 17, 2017 at 22:09

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
parseInt(window.getComputedStyle(bar).getPropertyValue('width')); did the trick! Thanks for pointing me in the right direction!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.