55
.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

9
  • 13
    I just leave it here: developer.mozilla.org/en-US/docs/Web/API/…. Commented Dec 4, 2013 at 14:24
  • 5
    include jQuery and use this is simpler and better $('.test').css( "margin" ); Commented Dec 4, 2013 at 14:33
  • 7
    @KareemHashem "Simple" not always "Better". Commented Dec 4, 2013 at 14:37
  • 1
    but in this case it is better than write many lines jQuery does in one line Commented Dec 4, 2013 at 14:39
  • 1
    @ZER0 In first case you should first remove style attribute node and then get style with getComputedStyle. Commented Dec 4, 2013 at 15:03

5 Answers 5

64

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

Sign up to request clarification or add additional context in comments.

9 Comments

Showing blank when i am using alert(style.margin);
include jQuery and use this is simpler and better $('.test').css( "margin" );
@Chinmay What browser do you use?
Latest browser Mozilla 25.0.1
hello @zzzzBov your code also working in chrome but not working in mozilla. :(
|
6

The accepted answer is the best way to get the computed values. I personally needed the pre-computed value. Say for instance 'height' being set to a 'calc()' value. I wrote the following jQuery function to access the value from the style sheet. This script handles nested 'media' and 'supports' queries, CORS errors, and should provide the final cascaded precomputed value for accessible properties.

$.fn.cssStyle = function() {
		var sheets = document.styleSheets, ret = [];
		var el = this.get(0);
		var q = function(rules){
			for (var r in rules) {
				var rule = rules[r];
				if(rule instanceof CSSMediaRule && window.matchMedia(rule.conditionText).matches){
					ret.concat(q(rule.rules || rule.cssRules));
				} else if(rule instanceof CSSSupportsRule){
					try{
						if(CSS.supports(rule.conditionText)){
							ret.concat(q(rule.rules || rule.cssRules));
						}
					} catch (e) {
						console.error(e);
					}
				} else if(rule instanceof CSSStyleRule){
					try{
						if(el.matches(rule.selectorText)){
							ret.push(rule.style);
						}
					} catch(e){
						console.error(e);
					}
				}
			}
		};
		for (var i in sheets) {
			try{
				q(sheets[i].rules || sheets[i].cssRules);
			} catch(e){
				console.error(e);
			}
		}
		return ret.pop();
	};
  
  // Your element
  console.log($('body').cssStyle().height);

1 Comment

I just tried this code with a very simple case, and it worked, but there's something that doesn't make sense to me. The code ret.concat(q(rule.rules || rule.cssRules)); looks like it expects something to be returned from the q function, but that function has no return value. I'm guessing that the real work is done by accumulating values in ret, but you would be accumulating undefined values this way.
3

Using jQuery:

   $('.class').css( "backgroundColor" );

Comments

2

Another approach (still experimental) could be computedStyleMap:

const computedStyleMap = document.getElementById('my-id').computedStyleMap();
computedStyleMap.get('overflow-x'); // {value: 'scroll'}
computedStyleMap.has('padding-right'); // false
computedStyleMap.entries(); // Iterator {}

1 Comment

1

I've just released an npm package for this purpose exactly. You can find it here on npm or github:

npm: https://www.npmjs.com/package/stylerjs

github: https://github.com/tjcafferkey/stylerjs

you would use it like so

var styles = styler('.class-name').get(['height', 'width']);

and styles would equal

{height: "50px", width: "50px"}

So you could just get the values like so

var height = styles.height;

1 Comment

Works like a charm. I removed the "export default " on the first line and added a <script src="js/styler.js"></script> to get it to work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.