iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

DOM CSS

JavaScript can read and change CSS in three ways: inline styles, computed styles, and CSS custom properties. The right choice depends on whether you're styling one element or theming the page.

Inline styles via style

JS
el.style.color = "#04AA6D";
el.style.backgroundColor = "#f1f1f1";    // camelCase, not kebab
el.style.setProperty("color", "red");    // works with custom properties too
el.style.setProperty("--brand", "#04AA6D");
el.style.removeProperty("background-color");

Read computed styles

JS
const cs = getComputedStyle(el);
cs.color;                  // "rgb(4, 170, 109)"
cs.getPropertyValue("--brand");

// Element-relative measurements that ALREADY account for CSS
el.offsetWidth;            // includes border + padding
el.clientWidth;            // includes padding, excludes border + scrollbar
el.getBoundingClientRect().width;   // floating-point precise

The fastest way: swap classes

JS
el.classList.add("active");
el.classList.toggle("dark", isDark);
el.dataset.state = "loading";   // pair with selectors like [data-state="loading"]

CSS custom properties — runtime theming

JS
// Set on :root affects the whole page
document.documentElement.style.setProperty("--brand", "#04AA6D");

// Read
getComputedStyle(document.documentElement).getPropertyValue("--brand").trim();
Tip: Reaching for .style.X = … in a loop forces layout recalculation. Prefer adding/removing a class — the browser batches the work.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from DOM CSS!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Set a CSS custom property from JavaScript.

el.style. ('--brand', '#04AA6D');

Test yourself

Q1. Read the final computed colour with…
Q2. Set a CSS custom property from JS with…
Q3. Fastest way to change many styles at once is…

Discussion

Loading…