8

I'm curious why this one

<div class = "overlay">
    fdsfsd
</div>
.overlay{
    width: 100px;
    height: 200px;
    background-color:red;
}
alert(document.getElementsByClassName("overlay")[0].style.width); 

is not alerting nothing. Of course I can write <div style = "width:100px"> then everthing works fine, but it is not good for me, I need css. Here you can find a jsfiddle demo

So exact question is: why this code is not alerting width of div and how alert it if width is given by css?

0

4 Answers 4

10

As noted elsewhere, the problem is that HTMLElement.style retrieves the values from the style attribute of the element; as you're setting your style with CSS, you need to instead use window.getComputedStyle(element, null).width:

var elem = document.getElementsByClassName("overlay")[0],
  width = window.getComputedStyle(elem, null).width;

console.log(width);
.overlay {
  width: 100px;
  height: 200px;
  background-color: red;
}
<div class="overlay">
  fdsfsd
</div>

References:

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

3 Comments

Don't know who down-voted this :/ but might want to parseInt
@Digigizmo: neither do I, it's a little annoying (but presumably they have their reasons). I'm not sure about using parseInt() (or parseFloat()), simply because the width without the units (even if JavaScript always returns lengths in px) seems a little meaningless; and there's no mention of wanting 'just' the numbers. If the question's updated to request that then I'll update, as-is it seems premature.
ye, I only mentioned it for awareness - generally you only fetch the width when you want to manipulate it or use the value in some other calculation.
5

The JavaScript .style only relates to inline styles on the element.

See Documentation.

If you want to get the width of an element you should use offsetWidth.

document.getElementsByClassName("overlay")[0].offsetWidth

http://jsfiddle.net/9kwap3zy/7/

Comments

1

The style gives access only to information which is put into elem.style. In your example style doesn’t tell anything about the margin defined in CSS. Use getComputedStyle().

var computedStyle = getComputedStyle(document.getElementsByClassName("overlay")[0], null)

alert(computedStyle.width);

jsfiddle demo

Comments

0

The .style is inline style="width:100px;" only...

If it's in CSS (rather than inline) you need getComputedStyle -

https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle

Comments

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.