The CSSStyleSheet.insertRule()
method inserts a new CSS rule into the current style sheet.
insertRule(rule)
insertRule(rule, index)
The newly inserted rule's index within the stylesheet's rule-list.
This snippet pushes a new rule onto the top of my stylesheet.
myStyle.insertRule("#blanc { color: white }", 0);
function addStylesheetRules(rules) {
const styleEl = document.createElement("style");
document.head.appendChild(styleEl);
const styleSheet = styleEl.sheet;
for (let i = 0; i < rules.length; i++) {
let j = 1,
rule = rules[i],
selector = rule[0],
propStr = "";
if (Array.isArray(rule[1][0])) {
rule = rule[1];
j = 0;
}
for (let pl = rule.length; j < pl; j++) {
const prop = rule[j];
propStr += `${prop[0]}: ${prop[1]}${prop[2] ? " !important" : ""};\n`;
}
styleSheet.insertRule(
`${selector}{${propStr}}`,
styleSheet.cssRules.length,
);
}
}