[javascript] Get a CSS value with JavaScript

I know I can set a CSS value through JavaScript such as:

document.getElementById('image_1').style.top = '100px';

But, can I get a current specific style value? I've read where I can get the entire style for the element, but I don't want to have to parse the whole string if I don't have to.

This question is related to javascript css

The answer is


The cross-browser solution without DOM manipulation given above does not work because it gives the first matching rule, not the last. The last matching rule is the one which applies. Here is a working version:

function getStyleRuleValue(style, selector) {
  let value = null;
  for (let i = 0; i < document.styleSheets.length; i++) {
    const mysheet = document.styleSheets[i];
    const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    for (let j = 0; j < myrules.length; j++) {
      if (myrules[j].selectorText && 
          myrules[j].selectorText.toLowerCase() === selector) {
        value =  myrules[j].style[style];
      }
    }
  }
  return value;
}  

However, this simple search will not work in case of complex selectors.


The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.

Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.

The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......

function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    // W3C standard way:
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hyphen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
            return letter.toUpperCase();
        });
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
            return (function(value) {
                var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft + "px";
                el.style.left = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
            })(value);
        }
        return value;
    }
}

Main reference stackoverflow


If you set it programmatically you can just call it like a variable (i.e. document.getElementById('image_1').style.top). Otherwise, you can always use jQuery:

<html>
    <body>
        <div id="test" style="height: 100px;">Test</div>
        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript">
            alert($("#test").css("height"));
        </script>
    </body>
</html>

As a matter of safety, you may wish to check that the element exists before you attempt to read from it. If it doesn't exist, your code will throw an exception, which will stop execution on the rest of your JavaScript and potentially display an error message to the user -- not good. You want to be able to fail gracefully.

var height, width, top, margin, item;
item = document.getElementById( "image_1" );
if( item ) {
  height = item.style.height;
  width = item.style.width;
  top = item.style.top;
  margin = item.style.margin;
} else {
  // Fail gracefully here
}

If you're into libraries, why not MyLibrary and getStyle.

The jQuery css method is misnamed, CSS is just one way of setting styles and doesn't necessarily represent the actual values of an element's style properties.


You can use getComputedStyle().

var element = document.getElementById('image_1'),
    style = window.getComputedStyle(element),
    top = style.getPropertyValue('top');

jsFiddle.


Use the following. It helped me.

document.getElementById('image_1').offsetTop

See also Get Styles.


Cross-browser solution to checking CSS values without DOM manipulation:

function get_style_rule_value(selector, style)
{
 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
   if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector)
   {
    return myrules[j].style[style];
   }
  }
 }
};

Usage:

get_style_rule_value('.chart-color', 'backgroundColor')

Sanitized version (forces selector input to lowercase, and allows for use case without leading ".")

function get_style_rule_value(selector, style)
{
 var selector_compare=selector.toLowerCase();
 var selector_compare2= selector_compare.substr(0,1)==='.' ?  selector_compare.substr(1) : '.'+selector_compare;

 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
    if (myrules[j].selectorText)
    {
     var check = myrules[j].selectorText.toLowerCase();
     switch (check)
     {
      case selector_compare  :
      case selector_compare2 : return myrules[j].style[style];
     }
    }
   }
  }
 }

In 2020

check before use

You can use computedStyleMap()

The answer is valid but sometimes you need to check what unit it returns, you can get that without any slice() or substring() string.

var element = document.querySelector('.js-header-rep');
element.computedStyleMap().get('padding-left');

_x000D_
_x000D_
var element = document.querySelector('.jsCSS');_x000D_
var con = element.computedStyleMap().get('padding-left');_x000D_
console.log(con);
_x000D_
.jsCSS {_x000D_
  width: 10rem;_x000D_
  height: 10rem;_x000D_
  background-color: skyblue;_x000D_
  padding-left: 10px;_x000D_
}
_x000D_
<div class="jsCSS"></div>
_x000D_
_x000D_
_x000D_