CSSOM and stylesheet APIs
Definition and purpose
The CSS Object Model exposes parsed stylesheets, rules and declarations as objects that JavaScript can inspect and, when permitted, change. Use these APIs for controlled mutations rather than concatenating untrusted CSS.
Insert and remove an approved rule
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a { color: blue; } </style> </head> <body> <p id="a">Approved status</p> <button id="add" type="button">Apply</button> <button id="remove" type="button">Undo</button> <script> const sheet=document.styleSheets[0]; let index=null; document.querySelector("#add").onclick=()=>{if(index===null) index=sheet.insertRule("#a { color: green; }",sheet.cssRules.length)}; document.querySelector("#remove").onclick=()=>{if(index!==null){sheet.deleteRule(index);index=null;}}; </script> </body></html>Apply appends a green rule, Undo removes only that rule. No network requests.
Syntax and mental model
document.styleSheets lists document stylesheets. cssRules is a live list; insertRule(rule,index) inserts one rule and returns its index. deleteRule(index) removes the rule at that current index, so track other mutations. Cross-origin sheets may throw SecurityError when reading rules. CSSStyleDeclaration.setProperty and removeProperty mutate declarations; constructed CSSStyleSheet objects can be adopted in supported contexts. Use fixed approved rule strings, feature detection and error handling.
Declaration mutation
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a { color: blue; } </style> </head> <body> <p id="a">Approved status</p> <script> document.querySelector("#a").style.setProperty("color","green"); </script> </body></html>The inline declaration overrides the ordinary author rule.
Common mistakes
Do not assume the index remains stable after other insertions or deletions. Do not bypass cross-origin restrictions.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Tokenization and parsing. Next lesson: Resolved style and geometry APIs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CSSOM and stylesheet APIs — knowledge check
Five questions on cssom and stylesheet apis.
What does insertRule return?
What is cssRules?
What may reading a cross-origin sheet throw?
Which method sets a declaration?
Why track rule-list mutations?