Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.getComputedStyle(): How to Discard properties with default values?

Hi I am developing an extension for Google Chrome and am using window.getComputedStyle() to get a particular property of a DOM element. This way, I am getting multiple properties and building a CSS. I want to discard the properties with default values. How can I do that? How can I know the default value of a property?

like image 608
U.P Avatar asked Dec 17 '10 14:12

U.P


1 Answers

Looking through the chromium source led me to: node.ownerDocument.defaultView.getMatchedCSSRules(node, '');

I used it to create this function that will return only the styles defined by the style property or a matched CSS rule. Anything that appears in getComputedStyle but not here would be default, but I'm guess that this returns what you are actually looking for: the styles without the defaults.

// WebKit only
function getStyle(node) {
  var styles = {};
  var rules = node.ownerDocument.defaultView.getMatchedCSSRules(node, '');

  var i = rules.length;
  while (i--) {
    merge(styles, rules[i].style)
  }
  merge(styles, node.style);

  return styles;

  function merge(obj, style) {
    var i = style.length;
    while(i--) {
      var name = style[i];
      obj[name] = style.getPropertyCSSValue(name);
    }
  }
}
like image 131
Hemlock Avatar answered Sep 22 '22 13:09

Hemlock