26

I found this getComputedStyle polyfill in a JavaScript plugin

if (!computed) {
  window.getComputedStyle = function(el) {
    this.el = el;
    this.getPropertyValue = function(prop) {
      var re = /(\-([a-z]){1})/g;
      if (prop === "float") {
        prop = "styleFloat";
      }
      if (re.test(prop)) {
        prop = prop.replace(re, function () {
          return arguments[2].toUpperCase();
        });
      }
      return el.currentStyle[prop] ? el.currentStyle[prop] : null;
    };
    return this;
  };
}

Is there any jQuery equivalent for getcomputedstyle();

1 Answers1

43

You can use the getter version of .css().

From doc

The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties.

like

$(el).css('color')
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 3
    but does this take into account browser defaults and/or user CSS? i suspect that's what @Arya is looking for with 'computed style' – Plato Oct 02 '13 at 13:02
  • 5
    @Plato: From the docs: "*The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties*" – Bergi Oct 02 '13 at 13:02
  • @Arya note that your polyfill may do more harm than good - just let jQuery do its thing. – Alnitak Oct 02 '13 at 13:04
  • 1
    Looks like it does get properties from user agent stylesheet: http://jsfiddle.net/c8RDW/ – Plato Oct 02 '13 at 13:09
  • 3
    jQuery x getComputedStyle are different... not same. Example a try `$('p:before').css('color','red')` is not work... only javascript is work a real. jQuery just plugin. – KingRider Dec 29 '16 at 15:35
  • CSS is not solution at all. For example how can you get RGB color data of semitransparent element? I suppose we still need to use native JS here. – Andrey Merkulov Aug 07 '20 at 18:07