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

Loading...

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?

Solutions/Answers:

Solution 1:

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

Solution 2:

This may be very, very tough, as there is no single way to tell where an element’s CSS rules come from. computedStyle mixes them all together to show the end result. Default values are by definition hard to pick out from that.

I have an alternative idea – if it applies in your situation:

  • Programmatically disable every style sheet involved in the page for a second. Disable all inline <style> elements from the DOM.

  • If, when all style sheets have been disabled, the computedStyle of the element is unchanged, you’re dealing with a default value.

You could even find out which style sheets contain rules applying to an element, by disabling the style sheets one by one, and keeping track of whether the computedStyle changes.

This is obviously rather complex and slow, but it’s the only safe way I can think of.

References

Loading...