Posted By

Jman on 03/28/09


Tagged

css javascript DOM


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Jman


getComputedStyle for IE


 / Published in: JavaScript
 

fix for IE, adds getComputedStyle method for the object window and getPropertyValue method for the object, which returns getComputedStyle

  1. if (!window.getComputedStyle) {
  2. window.getComputedStyle = function(el, pseudo) {
  3. this.el = el;
  4. this.getPropertyValue = function(prop) {
  5. var re = /(\-([a-z]){1})/g;
  6. if (prop == 'float') prop = 'styleFloat';
  7. if (re.test(prop)) {
  8. prop = prop.replace(re, function () {
  9. return arguments[2].toUpperCase();
  10. });
  11. }
  12. return el.currentStyle[prop] ? el.currentStyle[prop] : null;
  13. }
  14. return this;
  15. }
  16. }
  17.  
  18. EXAMPLE
  19.  
  20. window.onload = function() {
  21. var compStyle = window.getComputedStyle(document.getElementById('test'), "");
  22.  
  23. alert(compStyle.getPropertyValue("color"));
  24. alert(compStyle.getPropertyValue("float"));
  25. alert(compStyle.getPropertyValue("background-color"));
  26. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: RobertWHurst on September 20, 2012

This doesn't work correctly. GetComputed styles will always return a pixel value if possible. currentStyle returns the raw value.

for example if I have an element with a width of 50% get computed style would give me the width in pixels. You polyfill would incorrectly give me 50% instead of a pixel value.

You need to login to post a comment.