How to get CSS class property in Javascript?

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

Leave a Comment