Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 156 ยท The DOM

Styles and Classes

Change how elements look from JavaScript with classList, inline styles and CSS custom properties, and read final values with getComputedStyle.

JavaScript can change how anything on the page looks, but how you do it matters. You can flip a class and let your stylesheet do the work, write inline styles directly onto an element, or set a CSS custom property that your CSS then uses in many places. Each approach has a sweet spot.

In this lesson you will master classList, learn exactly what the style property can and can't do, drive CSS variables from JavaScript, and read the browser's final, computed values with getComputedStyle(). You will also see how to make changes animate smoothly with CSS transitions.

Prefer classes: classList

The cleanest way to change an element's appearance is to change its state, not its style. Add a class such as is-open or selected, and keep the actual colors, sizes and animations in CSS. Your JavaScript stays short, designers can adjust the look without touching scripts, and media queries, dark mode and hover styles keep working.

element.classList is a DOMTokenList with everything you need:

  • add("a", "b") โ€” add one or more classes (duplicates are ignored).
  • remove("a", "b") โ€” remove one or more (missing ones are ignored).
  • toggle("a") โ€” add if missing, remove if present; returns true if the class is now on.
  • toggle("a", force) โ€” with a boolean second argument, sets the class: on for true, off for false.
  • contains("a") โ€” true or false.
  • replace("old", "new") โ€” swap one class for another; returns false if old wasn't there.

The force form of toggle() deserves special attention. Instead of writing an if/else with add() and remove(), you can tie a class directly to a condition:

JavaScript
row.classList.toggle("overdue", dueDate < today);
input.classList.toggle("has-value", input.value !== "");
classList with a forced toggle

Notice the "hide finished" checkbox: it sets a single class on the container, and CSS hides every finished task inside it. One class change can restyle a whole section.

You may also see element.className, the full class attribute as one string. Assigning it replaces all classes, which is rarely what you want; prefer classList.

Inline styles with style

element.style gives you the element's inline styles, the ones in its style="โ€ฆ" attribute. Each CSS property is available in camelCase:

JavaScript
box.style.backgroundColor = "gold";   // background-color
box.style.marginTop = "12px";          // units are required
box.style.zIndex = "10";
box.style.backgroundColor = "";        // remove the inline value

A few rules make style behave predictably:

  • Always include units. box.style.width = 200 is ignored; "200px" works.
  • Invalid values are silently ignored. Setting color to "blu" does nothing, with no error.
  • Assign an empty string to remove an inline value, letting the stylesheet take over again.
  • It only reads inline styles. style.color is "" if the color comes from a stylesheet. To find the actual color, use getComputedStyle() (below).

For kebab-case names and custom properties there is a method form: style.setProperty("background-color", "gold"), style.getPropertyValue(...) and style.removeProperty(...). setProperty() also accepts a third argument, "important".

Inline styles are the right tool for values that are genuinely dynamic: a position that follows the pointer, a width that represents progress, a color the user picked. For fixed visual states, use a class.

CSS variables from JavaScript

CSS custom properties are the best bridge between JavaScript and CSS. Your script sets one number; your stylesheet decides how to use it โ€” in a width, a color, a transform, a calculation. Custom properties have to be set with setProperty(), because --names aren't valid JavaScript identifiers:

JavaScript
document.documentElement.style.setProperty("--accent", "#0a7");
card.style.setProperty("--progress", 0.75);

Set them on document.documentElement (the <html> element) to affect the whole page, or on one element to affect only it and its descendants, thanks to inheritance.

Driving CSS variables

Both sliders change a single variable each, and every panel, border and heading updates. To build a theme switcher, this is the pattern: a few variables on the root, and the whole design follows. (Persisting the user's choice is covered in localStorage and sessionStorage.)

Reading final values with getComputedStyle()

getComputedStyle(element) returns a read-only, live object containing the value of every CSS property after the cascade, inheritance and all stylesheets have been applied. Use it when you need to know what the browser actually uses.

JavaScript
const styles = getComputedStyle(button);
styles.color;                       // "rgb(255, 255, 255)"
styles.getPropertyValue("padding-left"); // "16px"
styles.display;                     // "inline-block"

Values come back resolved, usually in a normalized form: colors as rgb() strings, lengths in px, even if you wrote rem, em or a percentage. Shorthands like margin may or may not be available, so ask for the longhand (margin-top). A second argument reads a pseudo-element: getComputedStyle(el, "::before").content.

style vs getComputedStyle

Reading layout costs time. Asking for computed styles or sizes (like offsetWidth or getBoundingClientRect()) forces the browser to finish any pending style and layout work first. Doing that once is fine. Alternating reads and writes in a loop over hundreds of elements makes the browser recalculate layout again and again. Do all your reads first, then all your writes.

Showing and hiding

There are three common ways to hide something, and they are not equivalent:

  • The hidden property: panel.hidden = true. Semantic, simple, and removes the element from the accessibility tree. Note that a CSS rule like display: flex on the element overrides hidden, so add [hidden] { display: none !important; } to your CSS if you mix them.
  • A class that sets display: none or a visually hidden style. Best when you want to animate or vary the hiding by context.
  • style.display = "none". Works, but to show it again you have to remember the original display value. Prefer the first two.

Animating changes with transitions

When a class or variable changes, a CSS transition can animate between the old and new values. JavaScript just flips the state; CSS animates it.

Class changes with transitions

The button also updates aria-expanded, so screen reader users hear whether the drawer is open. Visual state and accessible state should always change together.

Choosing an approach

Situation Best tool
A fixed visual state (open, selected, error) classList
A continuously changing number (progress, position, hue) A CSS variable via style.setProperty()
A one-off dynamic value on one element element.style.property
Reading what the browser actually applied getComputedStyle()

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does row.classList.toggle("overdue", isLate) do when isLate is false?

    With a boolean second argument, toggle() sets the class: present for true, absent for false.
  2. 2. A paragraph is colored red by a stylesheet rule. What does p.style.color return?

    style only reflects inline styles. Use getComputedStyle(p).color to get the applied value.
  3. 3. Which line correctly sets a CSS custom property named --gap?

    Custom property names aren't valid JavaScript identifiers, so use setProperty() with the full -- name.
  4. 4. You wrote font-size: 1.5rem in CSS. What does getComputedStyle(el).fontSize usually return?

    Computed values are resolved, so relative lengths come back as pixels.
  5. 5. Why is box.style.width = 300 a bug?

    CSS lengths need units. Invalid values assigned through style are silently ignored; use "300px".

Summary

  • Change state with classList and keep visual details in CSS; toggle(name, force) ties a class to a condition.
  • element.style reads and writes only inline styles, uses camelCase names, needs units and ignores invalid values silently.
  • Set CSS variables with style.setProperty("--name", value), on the root for the whole page or on one element for local effect.
  • getComputedStyle() returns the final, resolved values the browser applies, such as colors in rgb() and lengths in px.
  • Batch layout reads before writes, keep ARIA state in sync with visual state, and let CSS transitions animate class changes.

Next: Creating and Removing Elements โ€” building new parts of the page with createElement(), templates and fragments.