How do you change CSS with JavaScript?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
Three approaches, in the order you should reach for them.
1. Toggle classes — the default choice
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open", isOpen); // second argument forces the state
el.classList.contains("active");
Styling stays in the stylesheet where it belongs, and you can change the design without touching JavaScript. This is what you want almost every time.
2. CSS custom properties — for dynamic values
When the value is computed rather than one of a few known states:
el.style.setProperty("--progress", `${percent}%`);
.bar { width: var(--progress); transition: width 0.2s; }
The rule lives in CSS, JavaScript supplies only the number. This keeps transitions and media queries working, which inline styles tend to break.
3. Inline styles — last resort
el.style.backgroundColor = "blue"; // camelCase for hyphenated properties
el.style.cssText = "color: red; margin: 4px";
Inline styles win over stylesheet rules, so they are hard to override later and mix concerns. Reserve them for values only JavaScript can know, such as a tooltip's measured position.
Reading styles
el.style.color only returns inline styles — it is empty for anything set by a stylesheet. To read the value actually in effect:
getComputedStyle(el).color; // "rgb(255, 0, 0)" — always resolved
Note it returns computed values, so em comes back in pixels and colours in rgb().
A performance warning
getComputedStyle and geometry reads like offsetHeight force the browser to flush pending layout. Alternating a read and a write inside a loop causes layout thrashing — batch all reads first, then all writes.
