We can read the CSS rules of any stylesheet by using a simple JavaScript solution.
Stylesheets are organized into an array-like structure of styleSheet objects. Every object, in turn, contains a list of CSS rules inside the cssRules array. A rule is made up of two distinct parts: a selectorText property which represents the selectors used in the rule block and a style.cssText property which is simply the set of style declarations within a rule.
Stylesheets can be accessed using an index just like a normal array. The first stylesheet on the page has index 0, the second 1 and so on.
'use strict';
const readRules = (css = 0) => {
let styleSheet = document.styleSheets[css];
let rules = styleSheet.cssRules;
let data = [];
for(let i = 0; i < rules.length; i++) {
let rule = rules[i];
if (!rule.selectorText) {
continue;
}
let datum = {
selector: rule.selectorText,
styles: rule.style.cssText
};
data.push(datum);
}
return data;
};
You can see the above code in action on the following page.