Skip to content

Instantly share code, notes, and snippets.

@willwillems
Created January 10, 2021 13:55
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 willwillems/95939fd96e97eaea6abff757fb3a0485 to your computer and use it in GitHub Desktop.
Save willwillems/95939fd96e97eaea6abff757fb3a0485 to your computer and use it in GitHub Desktop.
Get matching CSS rules for a DOM element using the new CSSOM stylesheet implementation
function getMatchingCSSRulesForEl (el) {
return [...document.styleSheets]
.filter(ss => { try { return ss.cssRules; } catch (e) { return false } })
.flatMap(e => [...e.cssRules].filter(r => el.matches(r.selectorText)))
}
@willwillems
Copy link
Author

Due to a weird CORS CSS implementation in Chrome the only reliable way to filter inaccessible styleSheets is to try to access them and fail.

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