api-member

Cssstylesheet.replace — CSS reference

Asynchronously replaces the rules of a constructed stylesheet, returning a promise for that sheet. It is not a method for replacing the text of a stylesheet owned by a style element. Adopt the sheet to apply its rules, and await completion before measuring the result.

Formal Syntax & Structure

css syntaxcss
await constructedSheet.replace("#a { color: blue; }")

Working Example

Example Snippetcss
<!doctype html><html lang="en"><meta charset="utf-8"><title>CSSStyleSheet.replace</title><style>body{margin:8px;font:16px/20px sans-serif;color:black;background:white}#a{color:green}</style><body><p id="a">Sample text</p><p>Run once, then reload the page to repeat from the original state.</p><button id="run" type="button">Run example</button><pre id="result" aria-live="polite"></pre><script>const target=document.getElementById('a');const sheet=document.styleSheets[0];async function demo(){const s=new CSSStyleSheet();document.adoptedStyleSheets=[s];const done=await s.replace("#a{color:blue}");return [done===s,s.cssRules.length,getComputedStyle(target).color];}document.getElementById('run').onclick=async()=>{try{document.getElementById('result').textContent=JSON.stringify(await demo());}catch(e){document.getElementById('result').textContent=e.name+': '+e.message;}};</script></body></html>
CSS Reference