Codectionary / Developer documentation / JavaScript

getComputedStyle() and element.style

element.style gives direct read/write access to an element's inline styles only - not styles applied via CSS classes or stylesheets. getComputedStyle() returns the actual final, computed value of any CSS property after all stylesheets, inheritance, and browser defaults are applied, regardless of where that style came from.

Syntax

element.style.propertyName = value;
getComputedStyle(element).propertyName

Examples

Setting Inline Styles Directly

Reading and writing an element's own inline style properties.

const box = document.querySelector("#box");

box.style.backgroundColor = "blue";
box.style.width = "200px";
box.style.fontSize = "1.5rem"; // camelCase for hyphenated CSS properties

console.log(box.style.backgroundColor); // "blue" - only reflects inline styles set this way

getComputedStyle() - The Real Rendered Value

Getting the actual applied style, regardless of where it came from (CSS file, class, or inline).

// Even if color is set via an external CSS class, not inline:
const box = document.querySelector("#box");
const styles = getComputedStyle(box);

console.log(styles.color);      // the actual rendered color, from any source
console.log(styles.fontSize);   // always returns a computed pixel value, like "16px"
console.log(box.style.color);   // "" - empty, since color was not set inline

Best practices

  • Use element.style for styles your own script sets directly - use CSS classes with classList for styles that come from a stylesheet
  • Use getComputedStyle() when you need to read the actual current visual value of a property, no matter its source
  • Remember getComputedStyle() returns resolved values (like pixels), not the original units used in the stylesheet (like rem or %)
  • Prefer toggling CSS classes over directly setting element.style in application code, for cleaner separation between structure/behavior and presentation

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation