Working with CSS

The CSS Object Model (CSSOM) is the DOM of stylesheets. getComputedStyle(el) returns read-only resolved values; el.style edits inline declarations; document.styleSheets[i].cssRules exposes rules from <style> and <link>; and new CSSStyleSheet() builds a constructable stylesheet that you attach through adoptedStyleSheets (Baseline since March 2023). The CSS Typed OM (attributeStyleMap, computedStyleMap()) returns numbers with units instead of strings; Chrome 1 and Safari 10 support it, Firefox 555 does not.

Reading and writing CSS from JavaScriptHTMLLive
<style>p { color: red; }</style>
<p style="background: orange">So a JavaScript function walks into a bar.</p>
<pre id="out"></pre>
<script>
  const p = document.querySelector('p');
  p.style.setProperty('color', 'blue', 'important');                   // inline declarations
  const rule = document.styleSheets[0].cssRules[0];                    // stylesheet rules
  const sheet = new CSSStyleSheet();                                   // constructable sheet
  sheet.replaceSync('pre { border-left: 4px solid green; padding-left: 8px; }');
  document.adoptedStyleSheets.push(sheet);
  const size = p.computedStyleMap().get('font-size');                  // CSS Typed OM
  document.querySelector('#out').textContent = [`computed: ${getComputedStyle(p).fontSize}`,
    `inline: ${p.style.cssText}`, `${rule.constructor.name}: ${rule.cssText}`,
    `typed OM: value ${size.value}, unit '${size.unit}'`].join('\n');
</script>
Browser output of Listing 8.9
Browser output of 9

One constructable sheet can be shared by the document and many shadow roots, and editing it restyles them all; Lit 310,034 styles its components this way. Rule type numbers are deprecated; check rule.constructor.name instead. Reading cssRules of a cross-origin sheet loaded without CORS throws a SecurityError.