CoderZone.org

Category: >> JavaScript >> Get the computed style of an element Bookmark and Share

<< lastnext >>

Snippet Name: Get the computed style of an element

Description: Gets the computed 'style' attribute of an element. Note that this may not be the same as the rendered style.

Also see:
» Easy Style Sheet Switcher

Comment: (none)

Author: CoderZone
Language: JAVASCRIPT
Highlight Mode: JAVASCRIPT
Last Modified: December 01st, 2010

// Example call of the function:
// getStyle(document.getElementById("container"), "font-size");
 
 
function getStyle(oElm, strCssRule){
  var strValue = "";
  if(document.defaultView && document.defaultView.getComputedStyle){
    strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
  }
  else if(oElm.currentStyle){
    strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
      return p1.toUpperCase();
    });
    strValue = oElm.currentStyle[strCssRule];
  }
  return strValue;
}
 
 
 
Add a comment 
benjamin rocheAug 15th, 2011 12:11pm
this doesnt get the "rendered style" of an element as in the appearance visable on screen. This returns the computed style, as in what a css attribute would be, if an element has an apparent background colour but it is in fact the parent element that is applying the colour the return value for "background-color" would be transparent
CoderZone AdminAug 15th, 2011 12:22pm
Benjamin is absolutely correct- this gets the computed style which often isn't the same as the rendered style. The snippet description has been updated. Thanks, Benjamin!
© coderzone.org | users online: 6