Chinu Chinu - 4 months ago 8
CSS Question

How to get CSS class property in Javascript?

.test {
width:80px;
height:50px;
background-color:#808080;
margin:20px;
}


HTML -

<div class="test">Click Here</div>


In JavaScript i want to get
margin:20px

Answer

For modern browsers you can use getComputedStyle:

var elem,
    style;
elem = document.querySelector('.test');
style = getComputedStyle(elem);
style.marginTop; //`20px`
style.marginRight; //`20px`
style.marginBottom; //`20px`
style.marginLeft; //`20px`

margin is a composite style, and not reliable cross-browser. Each of -top -right, -bottom, and -left should be accessed individually.

fiddle