Skip to content

Instantly share code, notes, and snippets.

@stephen-james
Last active December 23, 2015 23:59
Show Gist options
  • Save stephen-james/6713677 to your computer and use it in GitHub Desktop.
Save stephen-james/6713677 to your computer and use it in GitHub Desktop.
resolveAppliedStyle, taken from http://stackoverflow.com/questions/7786972/how-to-determine-if-width-has-px-or/7787148 with a few variable name changes to suit my preferences.
(function(){
var documentElement = document.documentElement,
matchesSelector =
documentElement.matchesSelector ||
documentElement.mozMatchesSelector ||
documentElement.webkitMatchesSelector ||
documentElement.msMatchesSelector ||
documentElement.oMatchesSelector;
if (!matchesSelector) {
throw new Error("no browser support for selector matching");
}
function resolveAppliedStyle(element, style) {
var styleSheets = document.styleSheets,
numberOfStyleSheets = styleSheets.length,
styleSheet,
styleSheetIndex,
rule,
rules,
numberOfRules,
ruleIndex,
appliedRule,
appliedRules = [],
appliedRuleIndex,
numberOfAppliedRules,
latestAppliedValue;
for(styleSheetIndex = 0; styleSheetIndex < numberOfStyleSheets; ++styleSheetIndex) {
styleSheet = styleSheets[styleSheetIndex];
rules = styleSheet.cssRules || styleSheet.rules;
if(!rules) {
continue;
}
numberOfRules = rules.length;
for(ruleIndex = 0; ruleIndex < numberOfRules; ++ruleIndex) {
rule = rules[ruleIndex];
if( matchesSelector.call( element, rule.selectorText ) ) {
appliedRules.push( rule );
}
}
}
numberOfAppliedRules = appliedRules.length;
if(!numberOfAppliedRules) {
return element.style[style];
}
for(appliedRuleIndex = 0; appliedRuleIndex < numberOfAppliedRules; ++appliedRuleIndex) {
appliedRule = appliedRules[appliedRuleIndex];
if( style in appliedRule.style ) {
latestAppliedValue = appliedRule.style[style];
}
}
return latestAppliedValue || element.style[style];
}
window.resolveAppliedStyle = resolveAppliedStyle;
})();
@stephen-james
Copy link
Author

note, does not take into consideration CSS specificity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment