The Document StyleSheets Property
We wanted to take a look at all the CSS rules for an entire site. We discovered the
The code below:
- Pulls all the styles sheets from the DOM
- Maps each one
- Collects the CSS rules for each
let styles = document.styleSheets;
this.getGetTexContent(styles);
private getTextContent(collection: StyleSheetList) {
let oneArray = Array.from(collection);
let cssRules = oneArray.map((stylesheet) => {
let ss: any = stylesheet;
try {
if (ss.rules) {
return ss.rules;
}
} catch (error) {}
});
debugger;
this.es.data.emit(cssRules);
}
We had to include the try catch because of this error.
Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet': Cannot access rules
CSSRuleList Internals
- The DOM contains the stylesheet list for entire site.
- Each stylesheet contains a CSSRuleList.
- Each Rule in that list may contain it's own CSSRuleList.
- Each (Rule) known as a CSSStyleRule looks like this:
CSSStyleRule {
selectorText: ".slider[_ngcontent-nko-c0]",
style: CSSStyleDeclaration,
styleMap: StylePropertyMap,
type: 1,
cssText: ".slider[_ngcontent-nko-c0] {
animation: 1s ease 0s 1 normal forwards running slidein; }",
…}
cssText: ".slider[_ngcontent-nko-c0] {
animation: 1s ease 0s 1 normal forwards running slidein; }"
parentRule: null
parentStyleSheet: CSSStyleSheet {
ownerRule: null,
cssRules: CSSRuleList,
rules: CSSRuleList,
type: "text/css",
href: null,
…}
selectorText: ".slider[_ngcontent-nko-c0]"
style: CSSStyleDeclaration {
0: "animation-duration",
1: "animation-timing-function",
2: "animation-delay",
3: "animation-iteration-count",
4: "animation-direction",
5: "animation-fill-mode",
6: "animation-play-state",
7: "animation-name",
alignContent: "",
alignItems: "",
alignSelf: "",
alignmentBaseline: "",
all: "",
…}
styleMap: StylePropertyMap {size: 8}
type: 1
Now that we've discovered this; maybe it's the foundation for yet another CSS tool, like this tool we created to see if we could develop a Css refactoring tool. What is shown is a table of all styles where we did no parsing at all.
Top comments (4)
What was the DOM exception thrown if you didn't use the try/catch?
Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet': Cannot access rules.
Ah looks like because of a CORS violation. I didn't know realize this would throw an error until tofsy. Thanks!
stackoverflow.com/questions/487536...
Thanks for posting link. FYI later today I'm posting this solution to GitHub. I'll let you know.