Javascript: Can i dynamically create a CSSStyleSheet object and insert it?

I know you said you didn't want to create an element, but that's genuinely the only way to do it. A few people have detailed this approach above, but i notice nobody covered off that HTMLStyleElement and HTMLLinkElement both have a neat sheet property to get direct access to their CSSStyleSheet:

var style = document.createElement("style");
document.head.appendChild(style); // must append before you can access sheet property
var sheet = style.sheet;

console.log(sheet instanceof CSSStyleSheet);

Much simpler than searching through document.styleSheets


There's a brand new proposal that makes it possible to directly call the CSSStyleSheet constructor. Doing what you want to looks like this:

// Construct the CSSStyleSheet
const stylesheet = new CSSStyleSheet();

// Add some CSS
stylesheet.replaceSync('body { background: #000 !important; }')
// OR stylesheet.replace, which returns a Promise instead

// Tell the document to adopt your new stylesheet.
// Note that this also works with Shadow Roots.
document.adoptedStyleSheets = [stylesheet];

Note that currently this only works on Chrome Canary, but hopefully other browsers will implement this feature soon.

Tags:

Javascript

Dom