fdsfsd.overlay{ width: 100px; height: 200px; background-color:r...">

Javascript Element Style

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

does not warn anything. Of course, I can write <div style = "width:100px"> then everything works fine, but this is not good for me, I need css. Here you can find jsfiddle demo

The exact question is: why does this code not warn the width of the div and how to warn it if the width is given by css?

+8
javascript css
source share
4 answers

JavaScript .style refers only to inline element styles.

See the documentation .

If you want to get the width of the element, you must use offsetWidth .

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

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

+5
source share

As noted elsewhere, the problem is that HTMLElement.style is extracting values ​​from the element's style attribute; since you are customizing your style with CSS, you need to 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> 

Literature:

+10
source share

The style gives access only to information that is placed in elem.style . In your example, the style says nothing about the margin defined in CSS. Use getComputedStyle () .

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

jsfiddle demo

+1
source share

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

If in CSS (not in a string) you need getComputedStyle -

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

0
source share

All Articles