Add a Stylesheet to the Document Root of a Page with JavaScript

October 2025

HTML

<div class="added-later">
  The color on this text comes 
  from the added stylesheet
</div>

Output

The color on this text comes from the added stylesheet
JavaScript
function addStyles() {
  const sheet = new CSSStyleSheet();
  const theStyles = `.added-later { color: red; }`;
  sheet.replaceSync(theStyles);
  document.adoptedStyleSheets.push(sheet);
}


addStyles();
end of line