CSS Manipulation in JavaScript
Introduction
You can change page appearance from JavaScript by toggling classes, editing inline styles, or using the CSSStyleSheet API. Most apps prefer CSS files for design and JS only for state-driven class names—this chapter shows both patterns safely.
Prerequisites
Class-Based Styling (Recommended)
html
<!-- styles.css: .card.active { border-color: blue; } -->
<div id="card" class="card">Hello</div>
<script>
const card = document.getElementById("card");
card.classList.add("active");
card.classList.toggle("hidden");
</script>Keeps presentation in CSS; JS only reflects state (active, hidden, dark).
Inline Styles via element.style
javascript
// Set one property at a time (camelCase)
const banner = document.querySelector("#banner");
if (banner) {
banner.style.backgroundColor = "#1e293b";
banner.style.color = "#f8fafc";
banner.style.padding = "12px";
}Reading computed layout often needs getComputedStyle:
javascript
const styles = getComputedStyle(banner);
console.log(styles.fontSize);CSS Custom Properties (Variables)
css
/* in stylesheet */
:root {
--accent: #3b82f6;
}javascript
// Update variable from JS
document.documentElement.style.setProperty("--accent", "#ef4444");Useful for themes without rewriting every rule.
dataset and Attribute Selectors
html
<button data-size="large">Buy</button>javascript
const btn = document.querySelector("button");
btn.dataset.size = "small";Pair with CSS [data-size="large"] { ... }.
matchMedia for Responsive JS
javascript
// Run logic when viewport matches
const mq = window.matchMedia("(max-width: 768px)");
function onChange(e) {
console.log(e.matches ? "mobile" : "desktop");
}
mq.addEventListener("change", onChange);
onChange(mq);Avoid Common Pitfalls
- Do not build large style strings from user input (XSS risk with
innerHTML+<style>) - Prefer
classListoverelement.className =for multiple classes - Heavy animation belongs in CSS (
transition,@keyframes)
Mini Example: Dark Mode Toggle
html
<style>
:root[data-theme="dark"] {
color-scheme: dark;
background: #0f172a;
color: #e2e8f0;
}
</style>
<button id="toggle">Theme</button>
<script>
const root = document.documentElement;
document.getElementById("toggle").addEventListener("click", () => {
const next = root.dataset.theme === "dark" ? "light" : "dark";
root.dataset.theme = next;
localStorage.setItem("theme", next);
});
const saved = localStorage.getItem("theme");
if (saved) root.dataset.theme = saved;
</script>FAQ
Change stylesheet file dynamically?
Load <link rel="stylesheet" href="..."> or swap href—rare in SPAs using bundlers.
element.style vs classes?
Classes scale better; inline styles suit one-off dynamic values (drag position).
Frameworks?
React/Vue bind className / class to state—the same class-toggle idea.