Get a CSS value with JavaScript

JavascriptCss

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

You can use getComputedStyle().

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

<img id="image_1">

jsFiddle.

Solution 2 - Javascript

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

Solution 3 - Javascript

Use the following. It helped me.

document.getElementById('image_1').offsetTop

See also Get Styles.

Solution 4 - Javascript

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];
     }
    }
   }
  }
 }

Solution 5 - Javascript

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>

Solution 6 - Javascript

In 2021

> 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');

var element = document.querySelector('.jsCSS');
var con = element.computedStyleMap().get('padding-left');
console.log(con);

.jsCSS {
  width: 10rem;
  height: 10rem;
  background-color: skyblue;
  padding-left: 10px;
}

<div class="jsCSS"></div>

Solution 7 - Javascript

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
}

Solution 8 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael PaulView Question on Stackoverflow
Solution 1 - JavascriptalexView Answer on Stackoverflow
Solution 2 - JavascriptAmir MovahediView Answer on Stackoverflow
Solution 3 - Javascriptuser843938View Answer on Stackoverflow
Solution 4 - JavascriptkarolfView Answer on Stackoverflow
Solution 5 - JavascriptadotoutView Answer on Stackoverflow
Solution 6 - JavascriptNisharg ShahView Answer on Stackoverflow
Solution 7 - JavascriptBryanHView Answer on Stackoverflow
Solution 8 - JavascriptjcdufourdView Answer on Stackoverflow