// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");
// Apply the stylesheet to a document
document.adoptedStyleSheets.push(sheet);Document: adoptedStyleSheets property / notebook
Document: adoptedStyleSheets property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
sheet.insertRule("* { background-color: blue; }");
// The document will now have blue background.// Create an element in the document and then create a shadow root:
const node = document.createElement("div");
const shadow = node.attachShadow({ mode: "open" });
// Adopt the same sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];