Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.