TIL: Another way to insert CSS with JS


var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

Get a reference to the first stylesheet in the document, and insert your rule in there. It’s more helpful when the first (all) stylesheets are inline, so there’s no origin conflicts.

Source


Another extension of the sheet.insertRule usage is below. Create your own sheet and add the rule to it. This way, there’s no origin conflict, and the rule can be disabled or enabled at will.


// create a style sheet and add rule
var borderStyleSheet = document.createElement("style");
document.head.appendChild(borderStyleSheet);
borderStyleSheet.sheet.insertRule("#myElement *{ outline: 1px solid red;}", 0);

// disable rule
borderStyleSheet.disabled = true;

// enable rule
borderStyleSheet.disabled = false;

// see existing stylesheets
console.log(document.styleSheets);