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?
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 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:
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); .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