avazwij avazwij - 2 months ago 8
CSS Question

How to read property value of a DIV which is set by a CSS class?

I have a DIV with a class:

.myClass {
width : 40px;
height: 40px;
display:block;
}


In HTML, I have declared:

<div class = "myClass"> Hello</div>


How can I read in JavaScript the value of the property "display" of this div?

I tried:

a = document.getElementsByClassName("myClass")
console.log(a[0].style.display)


But I am not seeing anything in the Console.

Answer

You need to calculate the "computed" style (the resulting style after applying all stylesheets. This is done by calling getComputedStyle().

var element = document.getElementsByClassName("myClass")[0];
var style = window.getComputedStyle(element).getPropertyValue('display');
console.log(style);
.myClass {
   width : 40px;
   height: 40px;
   display:block;
}
<div class="myClass"> Hello</div>