The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Set one inline declaration | element.style.setProperty("--accent", "#2563eb"); | View examples |
| Read a resolved value | const display = getComputedStyle(element).display; | View examples |
| Inspect a pseudo-element | const content = getComputedStyle(element, ":
:before").content; | View examples |
| Enumerate document sheets | for (const sheet of document.styleSheets) console.log(sheet.href); | View examples |
| Insert a complete rule | const index = sheet.insertRule(".notice {
color: #b91c1c;
} | View examples |
| Delete by rule index | sheet.deleteRule(index); | View examples |
| Construct a stylesheet | const themeSheet = new CSSStyleSheet(); | View examples |
| Replace rules synchronously | themeSheet.replaceSync(":host { color: CanvasText; }"); | View examples |
| Replace rules asynchronously | await themeSheet.replace(cssText); | View examples |
| Adopt into a shadow root | shadowRoot.adoptedStyleSheets = [...shadowRoot.adoptedStyleSheets, themeSheet]; | View examples |
| Set a typed length | element.attributeStyleMap.set("padding-top", CSS.px(16)); | View examples |
| Detect stylesheet adoption | const canAdopt = "adoptedStyleSheets" in Document.prototype && "replaceSync" in CSSStyleSheet.prototype; | View examples |
| Batch theme tokens | for (const [name, value] of Object.entries(tokens)) root.style.setProperty(name, value); | View examples |
| Prefer a class for state | document.documentElement.classList.toggle("theme-dark", isDark); | View examples |
The CSS Object Model exposes stylesheets, rules, declarations, and resolved values to JavaScript. Use classes and custom properties for ordinary state changes; reach for CSSOM mutation or constructed stylesheets when a system truly needs dynamic rules or shared shadow-root styling, and contain compatibility, security, and performance risks.
Step by step
Detailed examples
Separate declared, inline, and resolved styles
element.style represents only the element's inline declaration block. getComputedStyle() returns a live read-only CSSStyleDeclaration of resolved values after cascade and computation; reading layout-dependent properties may force pending style or layout work. Values may be serialized rather than preserving authored syntax, and visited-link styles are deliberately restricted for privacy.
const card = document.querySelector(".card");
const styles = getComputedStyle(card);
const currentGap = styles.gap;
card.style.setProperty("--card-accent", "#2563eb");
console.log({ currentGap }); Mutate rules only on accessible stylesheets
document.styleSheets lists associated sheets, but reading cssRules from a cross-origin sheet without the required CORS relationship throws SecurityError. insertRule() accepts exactly one valid rule and enforces hierarchy constraints; indices change after insertions and deletions. Keep a reference to your own same-origin sheet instead of searching and rewriting third-party CSS.
const style = document.createElement("style");
style.dataset.owner = "notification-system";
document.head.append(style);
const sheet = style.sheet;
const index = sheet.insertRule(".notice[data-level='error'] { border-color: #b91c1c; }");
// Later, while no other code has changed this sheet:
sheet.deleteRule(index); Share constructed sheets across compatible roots
new CSSStyleSheet() creates a constructed stylesheet. replaceSync() updates it synchronously; replace() returns a promise. Document and ShadowRoot expose adoptedStyleSheets, and one constructed sheet can be shared only with roots in the document where it was created. Mutation is observable by every adopter, which is efficient for shared themes but requires clear ownership. Keep a style-element fallback for older engines.
const css = `:host { display: block; color: var(--text, #111827); }`;
const root = document.querySelector("theme-card").shadowRoot;
if ("adoptedStyleSheets" in ShadowRoot.prototype && "replaceSync" in CSSStyleSheet.prototype) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(css);
root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
} else {
const style = document.createElement("style"); style.textContent = css; root.prepend(style);
} Use Typed OM only behind capability checks
CSS Typed OM represents values as objects such as CSSUnitValue instead of serialized strings. attributeStyleMap accesses inline declarations and computedStyleMap() returns computed typed values. Coverage differs across properties and engines, so detect the exact method and keep string-based CSSOM behavior. Structured values reduce parsing and unit mistakes but do not remove layout costs.
const panel = document.querySelector(".panel");
if (panel.attributeStyleMap && globalThis.CSS?.px) {
panel.attributeStyleMap.set("padding-top", CSS.px(16));
} else {
panel.style.paddingTop = "16px";
} Keep mutation secure, accessible, and cheap
Never concatenate untrusted text into CSS rules: CSS can trigger network requests, hide controls, and alter UI meaning even though it is not script. Prefer predefined classes and validate any constrained token. Batch writes separately from layout reads to avoid forced synchronous layout, cache shared sheets, and avoid replacing a whole sheet for a single state change. Preserve forced-colors, reduced-motion, zoom, and focus behavior in every dynamic theme.
const allowedThemes = new Set(["light", "dark", "contrast"]);
function applyTheme(name) {
if (!allowedThemes.has(name)) throw new TypeError("Unsupported theme");
const root = document.documentElement;
root.classList.remove("theme-light", "theme-dark", "theme-contrast");
root.classList.add(`theme-${name}`);
} Local code tester
Design the stylesheet-managed theme surface
Edit the theme tokens and state classes that a CSSOM integration would update while preserving focus and forced-color behavior.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



