Created
December 30, 2015 08:50
-
-
Save jimmont/d489fc0f070cc1b26832 to your computer and use it in GitHub Desktop.
return the styles for elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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