Skip to content

Instantly share code, notes, and snippets.

@DV8FromTheWorld
Created February 25, 2021 21:44
Show Gist options
  • Save DV8FromTheWorld/933d55f9fbe5dc6945d0e78b28285ef8 to your computer and use it in GitHub Desktop.
Save DV8FromTheWorld/933d55f9fbe5dc6945d0e78b28285ef8 to your computer and use it in GitHub Desktop.
get-css-rules.js
/**
* Iterates through all stylesheets loaded onto the page and returns an array of all css rules.
* Useful for getter a quick glance at roughly how many css selector rules there are on a page.
*/
function getCssRules() {
const skipped = {}
const rules = Array.from(document.styleSheets)
.flatMap(sheet => Array.from(sheet.rules)
.flatMap(rule => {
const ruleType = rule.constructor.name
if (ruleType === 'CSSMediaRule') { //Media rule
return Array.from(rule.cssRules).map(mediaRule => `@media(${rule.conditionText}) ${mediaRule.selectorText}`)
}
if (!rule.selectorText) {
skipped[ruleType] = (skipped[ruleType] || 0) + 1
return false
}
return rule.selectorText || rule
})
)
.filter(rule => !!rule)
if (Object.keys(skipped)) {
/* eslint-disable-next-line no-console */
console.log("Skipped rules", skipped)
}
return rules
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment