Skip to content

Instantly share code, notes, and snippets.

@jimmont
Created December 30, 2015 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmont/d489fc0f070cc1b26832 to your computer and use it in GitHub Desktop.
Save jimmont/d489fc0f070cc1b26832 to your computer and use it in GitHub Desktop.
return the styles for elements
function styleRulesFor(elementList){
var el, i, out = [], allRules, getMatchedCSSRules, getComputedStyle = window.getComputedStyle;
if(!(getMatchedCSSRules=window.getMatchedCSSRules)){
// this is very slow
allRules = function(){
// setup when needed
var rules = [], i = 0, sheet, styleSheets = el.ownerDocument.styleSheets;
while(sheet = styleSheets[i++]){
rules.push.apply(rules, sheet.rules||[]);
};
allRules = function(){
return rules;
};
return rules;
};
var matcher = function(el, selector){
try{
return el.matches(selector);
}catch(err){ };
};
getMatchedCSSRules = function(el){
var i = 0, rule, match = matcher, rules = allRules(), out = [], selectors, selector, j;
while(rule = rules[i++]){
if(!(selector = rule.selectorText)) continue;
j = 0;
selectors = selector.split(',');
while(selector = selectors[j++]){
if(match(el, selector)){
out.push(rule);
break;
};
};
};
return out;
};
};
i = 0;
while(el = elementList[i++]){
if(el.sheet){
out.push({
node: el
,rules: el.sheet
});
continue;
};
out.push({
node: el
,rules: getMatchedCSSRules(el)
,computed: getComputedStyle(el)
,attribute: el.getAttribute('style')
});
};
return out;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment