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?
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?
Share Improve this question asked Dec 17, 2010 at 14:57 U.PU.P 7,4427 gold badges41 silver badges63 bronze badges2 Answers
Reset to default 8Looking 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);
}
}
}
This may be very, very tough, as there is no single way to tell where an element's CSS rules e from. putedStyle
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
putedStyle
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 putedStyle changes.
This is obviously rather plex and slow, but it's the only safe way I can think of.