Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript element style

Tags:

javascript

css

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?

like image 889
mondayguy Avatar asked Feb 22 '15 13:02

mondayguy


People also ask

What does element style mean?

element. style is a part of your browser devtools that indicates the inline style of the element which has a higher specificity value than any CSS selectors. That inline styles may be added by a JavaScript code, if so, you can override that declarations by using !


2 Answers

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:

  • HTMLElement.style.
  • window.getComputedStyle().
like image 52
David Thomas Avatar answered Sep 22 '22 01:09

David Thomas


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/

like image 33
Ashley Medway Avatar answered Sep 20 '22 01:09

Ashley Medway