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

Chris Bier
  • 14,183
  • 17
  • 67
  • 103
Chinmay235
  • 3,236
  • 8
  • 62
  • 93
  • 13
    I just leave it here: https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle#Example. – VisioN Dec 04 '13 at 14:24
  • you can also read this [post](http://stackoverflow.com/questions/10693845/can-getelementsbyclassname-change-style) hope it helps – Franck Ngako Dec 04 '13 at 14:30
  • 5
    include jQuery and use this is simpler and better $('.test').css( "margin" ); – Kareem Hashem Dec 04 '13 at 14:33
  • 7
    @KareemHashem "Simple" not always "Better". – Givi Dec 04 '13 at 14:37
  • 1
    but in this case it is better than write many lines jQuery does in one line – Kareem Hashem Dec 04 '13 at 14:39
  • Assuming you have the same `test` class, but also an inline style: `
    Click Here
    ` do you want to have the `margin` defined by the class (20px) or the margin applied to the element (that can be 20px without inline and 10px with inline)? In the second case the `getComputedStyle` is ok, as the others says, in the first case you need a different approach.
    – ZER0 Dec 04 '13 at 14:47
  • Sorry this is `internal` or `external` css – Chinmay235 Dec 04 '13 at 14:50
  • 1
    @ZER0 In first case you should first remove style attribute node and then get style with `getComputedStyle`. – Givi Dec 04 '13 at 15:03
  • @Givi, no. In the first case you should access directly to the css rule. Assuming for instance you have: `
    Click here
    ` where both of them are set the `margin`. If you want the margin applied, `getComputedStyle` is fine. If you want the margin of `test`, then you need a different approach. Because the question is not clear about that – it want the margin from `test`? Or the margin applied to the element? – I just highlight that fact, in order to be sure we understand the original request.
    – ZER0 Dec 04 '13 at 15:08

5 Answers5

60

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

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Showing blank when i am using `alert(style.margin);` – Chinmay235 Dec 04 '13 at 14:36
  • 5
    include jQuery and use this is simpler and better $('.test').css( "margin" ); – Kareem Hashem Dec 04 '13 at 14:37
  • 1
    @Chinmay What browser do you use? – VisioN Dec 04 '13 at 14:42
  • Latest browser `Mozilla 25.0.1` – Chinmay235 Dec 04 '13 at 14:44
  • hello @zzzzBov your code also working in chrome but not working in mozilla. :( – Chinmay235 Dec 04 '13 at 14:47
  • @Chinmay for me it's working in all modern browsers *(Chrome, Opera, Mozilla, IE11)* – Givi Dec 04 '13 at 14:51
  • @Chinmay, wrote this quick and had to run to a meeting. Turns out that the composite `margin` isn't cross-browser compatible, but the individual `marginTop` etc properties appear to work. The general idea works, but I hadn't tested the code cross browser. – zzzzBov Dec 04 '13 at 17:30
  • this solution works, but what if you want to get a lets say width that is set to 80%, and you want to see if it is percentages or pixels, this won't work – Andrejs Gubars Dec 15 '16 at 11:58
  • @andrejs well, considering that wasn't what was asked, it's not included in my answer. There are other questions that cover accessing the calculated values of percentages. – zzzzBov Dec 15 '16 at 12:38
5

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);
Bernesto
  • 1,368
  • 17
  • 19
  • 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. – kshetline Jul 29 '21 at 00:37
3

Using jQuery:

   $('.class').css( "backgroundColor" );
Jonathan
  • 6,741
  • 7
  • 52
  • 69
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 {}
Rafael Affonso
  • 181
  • 3
  • 6
  • 1
    [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap#browser_compatibility) – djvg Mar 13 '23 at 10:20
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;
dx_over_dt
  • 13,240
  • 17
  • 54
  • 102
codebytom
  • 418
  • 4
  • 12
  • Works like a charm. I removed the "export default " on the first line and added a `` to get it to work. – Jan Oct 14 '18 at 19:44