The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Set one inline declarationelement.style.setProperty("--accent", "#2563eb");View examples
Read a resolved valueconst display = getComputedStyle(element).display;View examples
Inspect a pseudo-elementconst content = getComputedStyle(element, ": :before").content;View examples
Enumerate document sheetsfor (const sheet of document.styleSheets) console.log(sheet.href);View examples
Insert a complete ruleconst index = sheet.insertRule(".notice { color: #b91c1c; }View examples
Delete by rule indexsheet.deleteRule(index);View examples
Construct a stylesheetconst themeSheet = new CSSStyleSheet();View examples
Replace rules synchronouslythemeSheet.replaceSync(":host { color: CanvasText; }");View examples
Replace rules asynchronouslyawait themeSheet.replace(cssText);View examples
Adopt into a shadow rootshadowRoot.adoptedStyleSheets = [...shadowRoot.adoptedStyleSheets, themeSheet];View examples
Set a typed lengthelement.attributeStyleMap.set("padding-top", CSS.px(16));View examples
Detect stylesheet adoptionconst canAdopt = "adoptedStyleSheets" in Document.prototype && "replaceSync" in CSSStyleSheet.prototype;View examples
Batch theme tokensfor (const [name, value] of Object.entries(tokens)) root.style.setProperty(name, value);View examples
Prefer a class for statedocument.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

01

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.

Read once, then update through a token
const card = document.querySelector(".card");
const styles = getComputedStyle(card);
const currentGap = styles.gap;
card.style.setProperty("--card-accent", "#2563eb");
console.log({ currentGap });
Back to quick reference ↑
02

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.

Own and safely remove a dynamic rule
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);
Back to quick reference ↑
03

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.

Adopt one component sheet with a fallback
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);
}
Back to quick reference ↑
04

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.

Typed length with a string fallback
const panel = document.querySelector(".panel");
if (panel.attributeStyleMap && globalThis.CSS?.px) {
  panel.attributeStyleMap.set("padding-top", CSS.px(16));
} else {
  panel.style.paddingTop = "16px";
}
Back to quick reference ↑
05

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.

Apply a validated theme through classes
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}`);
}
Back to quick reference ↑

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.

Runs in your browser
Preview

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. CSS Working GroupCSS Object Model (CSSOM)drafts.csswg.org
  2. CSS Working GroupCSSOM: adoptedStyleSheetsdrafts.csswg.org
  3. World Wide Web ConsortiumCSS Typed OM Level 1w3.org
  4. World Wide Web ConsortiumCSS Scoping Module Level 1w3.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback