# DOM Styling

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: DOM Manipulation
Source: https://www.devtutorials.ai/learn/javascript/dom/dom-styling

> Changing inline styles, class-based styling, reading final styles with getComputedStyle, setting custom properties, and adding, removing, toggling and checking classes through classList and the DOMTokenList it returns.

## What Is DOM Styling?

**DOM styling** = changing how an element looks with JavaScript while the page runs.

- **Inline style:** `el.style.color = "red"`, written onto one element.
- **Class-based:** `el.classList.add("shipped")`, and the stylesheet decides the look.
- **`classList`** = a `DOMTokenList` with `add`, `remove`, `toggle`, `contains`, `replace`.

**Simple lesson:** JavaScript switches classes on and off; CSS decides colours and sizes.

### A Real-World Example

An order badge says **Packing** in yellow.
When the order ships, JavaScript runs `badge.classList.replace("packing", "shipped")`.
The stylesheet makes `.shipped` green, so a designer can change the green without touching JavaScript.

<figure className="ts-fig">
  <svg viewBox="0 0 560 160" role="img" aria-label="A badge switches between a yellow packing look and a green shipped look as its class changes." width="100%">
    <rect x="0" y="0" width="560" height="160" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <text x="280" y="34" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#475569">badge.classList.replace("packing", "shipped")</text>
    <rect x="200" y="58" width="160" height="44" rx="22" fill="#fde68a" stroke="#d97706"><animate attributeName="fill" values="#fde68a;#fde68a;#bbf7d0;#bbf7d0" keyTimes="0;0.45;0.55;1" dur="3s" repeatCount="indefinite" /><animate attributeName="stroke" values="#d97706;#d97706;#16a34a;#16a34a" keyTimes="0;0.45;0.55;1" dur="3s" repeatCount="indefinite" /></rect>
    <text x="280" y="86" textAnchor="middle" fontSize="13" fill="#334155">Order 1001</text>
    <text x="280" y="135" textAnchor="middle" fontSize="12" fill="#475569">class="badge packing" → class="badge shipped"</text>
  </svg>
  <figcaption>One class change, a whole new look from the stylesheet.</figcaption>
</figure>

Each box is a small live page with its own `<style>` block. Edit the CSS or the script and run it again.

## What You Will Learn

1. Inline styles with `style`, and `getComputedStyle()`.
2. Why class-based styling is usually better.
3. Adding, removing and toggling classes.
4. Custom properties with `style.setProperty()`.
5. `DOMTokenList`: `add`, `remove`, `toggle`, `contains`, `replace`.

## CSS manipulation

Two ways to change styles after load:

1. Write a style onto the element (inline style).
2. Add or remove a class, and let the stylesheet do the rest.

### Inline styles

`el.style.backgroundColor = "..."` writes into the `style` attribute. CSS names with dashes become **camelCase** (`background-color` → `backgroundColor`).

```dom runnable title="Setting inline styles writes them into the element's style attribute"
<p id="status">Order 1001: packing</p>
<script>
  const status = document.getElementById("status");

  status.style.color = "white";
  status.style.backgroundColor = "#2563eb";
  status.style.padding = "8px";

  console.log(status.outerHTML);
  console.log("color property:", status.style.color);
</script>
```

Expected output:

```text
<p id="status" style="color: white; background-color: rgb(37, 99, 235); padding: 8px;">Order 1001: packing</p>
color property: white
```

**Why "inline"?** The style is written inside the element's tag.

### Class-based styling

Describe a look once in CSS; JavaScript adds the class. Removing it undoes the whole look in one call.

```dom runnable title="One class carries a whole look, and removing it undoes the whole look"
<style>
  .shipped { color: white; background-color: #16a34a; padding: 8px; }
</style>
<p id="status">Order 1001: shipped</p>
<script>
  const status = document.getElementById("status");

  status.classList.add("shipped");
  console.log("with the class:", status.outerHTML);
  console.log("background:", getComputedStyle(status).backgroundColor);

  status.classList.remove("shipped");
  console.log("without it:", status.outerHTML);
  console.log("background:", getComputedStyle(status).backgroundColor);
</script>
```

Expected output:

```text
with the class: <p id="status" class="shipped">Order 1001: shipped</p>
background: rgb(22, 163, 74)
without it: <p id="status" class="">Order 1001: shipped</p>
background: rgba(0, 0, 0, 0)
```

Add a class and let CSS decide the look. Use inline styles only for values the script works out live, like a width from data or a drag position.

### Changing style values

- Every value is a string.
- Lengths need a unit like `px` or `%`; a bare number is ignored.
- `""` clears the inline style.

```dom runnable title="A missing unit is ignored, and an empty string clears a style"
<div id="bar" style="width: 50%">Progress</div>
<script>
  const bar = document.getElementById("bar");
  console.log("start:", bar.style.width);

  bar.style.width = 80;
  console.log("after setting 80 with no unit:", bar.style.width);

  bar.style.width = "80%";
  console.log("after setting \"80%\":", bar.style.width);

  bar.style.width = "";
  console.log("after clearing:", JSON.stringify(bar.style.width));
  console.log(bar.outerHTML);
</script>
```

Expected output:

```text
start: 50%
after setting 80 with no unit: 50%
after setting "80%": 80%
after clearing: ""
<div id="bar" style="">Progress</div>
```

`style` sees **only inline** styles. `getComputedStyle(el)` shows the final result from every source:

```dom runnable title="style reads only inline styles, and getComputedStyle reads the final result"
<style>
  #card { padding: 12px; color: rgb(30, 41, 59); }
</style>
<div id="card" style="margin: 4px">Order 1001 for Asha</div>
<script>
  const card = document.getElementById("card");

  console.log("style.margin:", JSON.stringify(card.style.margin));
  console.log("style.padding:", JSON.stringify(card.style.padding));
  console.log("computed padding:", getComputedStyle(card).padding);
  console.log("computed color:", getComputedStyle(card).color);
</script>
```

Expected output:

```text
style.margin: "4px"
style.padding: ""
computed padding: 12px
computed color: rgb(30, 41, 59)
```

### Adding and removing classes

`classList.add()` and `classList.remove()` change one class and leave the others alone.

```dom runnable title="Moving an order badge from one status class to another"
<style>
  .badge { padding: 4px 8px; border-radius: 4px; }
  .packing { background-color: #fef3c7; }
  .shipped { background-color: #dcfce7; }
</style>
<span id="badge" class="badge packing">Packing</span>
<script>
  const badge = document.getElementById("badge");
  console.log("before:", badge.className);

  badge.classList.remove("packing");
  badge.classList.add("shipped");
  badge.textContent = "Shipped";

  console.log("after:", badge.className);
</script>
```

Expected output:

```text
before: badge packing
after: badge shipped
```

### Toggling classes

`toggle()` adds the class if missing, removes it if present, and returns `true`/`false`. Great for open/closed menus. (**DOM Events and Forms** covers `addEventListener`.)

```dom runnable title="Each click toggles the open class on the menu"
<style>
  #menu { display: none; }
  #menu.open { display: block; }
</style>
<button id="menu-button">Menu</button>
<ul id="menu"><li>Orders</li><li>Customers</li></ul>
<script>
  const button = document.getElementById("menu-button");
  const menu = document.getElementById("menu");

  button.addEventListener("click", () => {
    const isOpen = menu.classList.toggle("open");
    console.log("menu open?", isOpen, "| display:", getComputedStyle(menu).display);
  });

  // Two clicks, made by the script so the output appears straight away.
  button.click();
  button.click();
</script>
```

Expected output:

```text
menu open? true | display: block
menu open? false | display: none
```

### Changing CSS styles

`style.setProperty("--fill", "75%")` sets a style by its CSS name, including **custom properties**. JavaScript gives a number; CSS decides how to draw it.

```dom runnable title="JavaScript sets a number, and CSS decides how to draw it"
<style>
  .progress { background-color: #e2e8f0; height: 12px; }
  .progress-fill { background-color: #2563eb; height: 12px; width: var(--fill, 0%); }
</style>
<div class="progress"><div id="fill" class="progress-fill"></div></div>
<script>
  const fill = document.getElementById("fill");
  const ordersPacked = 3;
  const ordersTotal = 4;

  fill.style.setProperty("--fill", `${(ordersPacked / ordersTotal) * 100}%`);

  console.log("custom property:", fill.style.getPropertyValue("--fill"));
  console.log(fill.outerHTML);

  fill.style.removeProperty("--fill");
  console.log("after removeProperty:", fill.outerHTML);
</script>
```

Expected output:

```text
custom property: 75%
<div id="fill" class="progress-fill" style="--fill: 75%;"></div>
after removeProperty: <div id="fill" class="progress-fill" style=""></div>
```

`el.style.cssText = "color: white; padding: 8px"` sets several styles at once, but **replaces** every inline style already there.

## DOMTokenList

### DOMTokenList basics

A **DOMTokenList** is a list of separate words from one attribute. Each word is a **token**. No duplicates, kept in order, has `length` and works with `for...of`.

```dom runnable title="A DOMTokenList splits one attribute into separate tokens"
<span id="badge" class="badge   shipped urgent">Order 1001</span>
<script>
  const tokens = document.getElementById("badge").classList;

  console.log("type:", tokens.constructor.name);
  console.log("length:", tokens.length);
  console.log("first token:", tokens[0]);
  console.log("as an array:", [...tokens].join(" | "));
  console.log("value:", JSON.stringify(tokens.value));
</script>
```

Expected output:

```text
type: DOMTokenList
length: 3
first token: badge
as an array: badge | shipped | urgent
value: "badge   shipped urgent"
```

**Why "token"?** A token is one piece cut out of a longer string.

### `classList`

The `DOMTokenList` for the `class` attribute, always in step with it.

```dom runnable title="classList and the class attribute always agree"
<p id="note" class="card">Order 1001 for Asha</p>
<script>
  const note = document.getElementById("note");
  const classes = note.classList;

  classes.add("urgent");
  console.log("attribute after classList.add:", note.getAttribute("class"));

  note.className = "card paid";
  console.log("classList after className changed:", [...classes].join(", "));
  console.log("same list object as before?", classes === note.classList);
</script>
```

Expected output:

```text
attribute after classList.add: card urgent
classList after className changed: card, paid
same list object as before? true
```

### `add()`

Adds one or more names. One already there is not added again.

```dom runnable title="add accepts several names and never duplicates one"
<p id="order" class="card">Order 1001</p>
<script>
  const order = document.getElementById("order");

  order.classList.add("urgent", "paid");
  console.log("after adding two:", order.className);

  order.classList.add("urgent");
  console.log("after adding urgent again:", order.className);
</script>
```

Expected output:

```text
after adding two: card urgent paid
after adding urgent again: card urgent paid
```

### `remove()`

Removes one or more names. A missing one is ignored, no error.

```dom runnable title="remove accepts several names and ignores one that is missing"
<p id="order" class="card urgent paid">Order 1001</p>
<script>
  const order = document.getElementById("order");

  order.classList.remove("urgent", "paid");
  console.log("after removing two:", order.className);

  order.classList.remove("cancelled");
  console.log("after removing a missing class:", order.className);
</script>
```

Expected output:

```text
after removing two: card
after removing a missing class: card
```

### `toggle()`

- One argument: flips the class, returns whether it is now present.
- Two arguments: `toggle("paid", true)` always adds; `toggle("paid", false)` always removes.

```dom runnable title="toggle flips with one argument, and follows a boolean with two"
<p id="a" class="card">Order 1001</p>
<p id="b" class="card paid">Order 1002</p>
<script>
  const a = document.getElementById("a");
  console.log("flip:", a.classList.toggle("urgent"), "→", a.className);
  console.log("flip again:", a.classList.toggle("urgent"), "→", a.className);

  const orders = [
    { element: a, isPaid: true },
    { element: document.getElementById("b"), isPaid: false },
  ];

  for (const order of orders) {
    order.element.classList.toggle("paid", order.isPaid);
    console.log(order.element.id, "should be paid:", order.isPaid, "→", order.element.className);
  }
</script>
```

Expected output:

```text
flip: true → card urgent
flip again: false → card
a should be paid: true → card paid
b should be paid: false → card
```

### `contains()`

`true` or `false`, changes nothing. It checks whole tokens, so `"paid"` does not match `"unpaid"`.

```dom runnable title="contains answers a yes or no question about one class"
<ul>
  <li class="order paid">Order 1001 for Asha</li>
  <li class="order">Order 1002 for Ravi</li>
  <li class="order paid">Order 1003 for Meera</li>
</ul>
<script>
  for (const item of document.querySelectorAll(".order")) {
    const label = item.classList.contains("paid") ? "paid" : "waiting for payment";
    console.log(item.textContent + ":", label);
  }
</script>
```

Expected output:

```text
Order 1001 for Asha: paid
Order 1002 for Ravi: waiting for payment
Order 1003 for Meera: paid
```

### Working with class tokens

A token is one word: no spaces, not empty. Breaking the rule throws an error.

```dom runnable title="A token with a space in it is refused"
<p id="order" class="card">Order 1001</p>
<script>
  const order = document.getElementById("order");

  try {
    order.classList.add("paid urgent");
  } catch (error) {
    console.log("adding \"paid urgent\":", error.name);
  }

  try {
    order.classList.add("");
  } catch (error) {
    console.log("adding an empty string:", error.name);
  }

  order.classList.add("paid", "urgent");
  console.log("adding them separately:", order.className);
</script>
```

Expected output:

```text
adding "paid urgent": InvalidCharacterError
adding an empty string: SyntaxError
adding them separately: card paid urgent
```

`replace(old, new)` swaps a token in the same position, and returns `true` if `old` was found.

```dom runnable title="replace swaps one status class for another, keeping its position"
<span id="badge" class="badge packing large">Order 1001</span>
<script>
  const badge = document.getElementById("badge");

  console.log("packing → shipped:", badge.classList.replace("packing", "shipped"));
  console.log("classes now:", badge.className);

  console.log("cancelled → refunded:", badge.classList.replace("cancelled", "refunded"));
  console.log("classes now:", badge.className);
</script>
```

Expected output:

```text
packing → shipped: true
classes now: badge shipped large
cancelled → refunded: false
classes now: badge shipped large
```

Avoid `el.className += " paid"`. Twice gives `paid paid`, and string edits can cut `unpaid` into `un`. `classList` works on whole tokens.

## Styling on a Web Page

Each order line gets a status class. Buttons move it along with `replace()`, and `toggle(..., force)` keeps "urgent" in step with the data. A progress bar uses a custom property.

```js runnable preview="status-board" title="Status badges driven by classList"
const style = document.createElement("style");
style.textContent = `
  .packing { color: #92400e; } .shipped { color: #166534; } .delivered { color: #1e40af; }
  .urgent { font-weight: bold; } .bar { height: 6px; background: #e2e8f0; }
  .bar > div { height: 100%; width: var(--done, 0%); background: #16a34a; }`;
document.head.append(style);

const steps = ["packing", "shipped", "delivered"];
const orders = [{ id: 1001, urgent: true }, { id: 1002, urgent: false }];
const list = document.querySelector("#orders");

for (const order of orders) {
  const li = document.createElement("li");
  li.textContent = `#${order.id} `;
  li.classList.add("packing");
  li.classList.toggle("urgent", order.urgent);
  const bar = document.createElement("div");
  bar.className = "bar";
  bar.innerHTML = "<div></div>";
  const next = document.createElement("button");
  next.textContent = "Next step";
  next.addEventListener("click", () => {
    const current = steps.find((s) => li.classList.contains(s));
    const i = steps.indexOf(current);
    if (i < steps.length - 1) li.classList.replace(current, steps[i + 1]);
    bar.style.setProperty("--done", `${((i + 1) / (steps.length - 1)) * 100}%`);
    console.log(`#${order.id}:`, li.className);
  });
  li.append(next, bar);
  list.append(li);
}
```

Press **Next step** twice on an order: the colour changes with each class, and the bar fills through `--done`.

**Easy way to remember:** **class** for the look, **style** only for live numbers, **classList** never by hand.

## TL;DR

- `el.style.camelCase = "value"` with units; `""` clears it.
- `style` reads only inline styles; `getComputedStyle()` reads the final style.
- Prefer classes: `classList.add/remove/toggle/replace/contains`.
- `toggle(name, boolean)` follows your data instead of flipping blindly.
- `style.setProperty("--name", value)` hands numbers to CSS.

## Try this

In the `toggle()` box, set `isPaid: true` for element `b`. Its line now shows `card paid`: the force argument only makes the class match the value.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `el.style.width = 200` | Numbers are pixels | Add the unit: `"200px"` | Nothing changes |
| Reading `el.style.color` for stylesheet colours | `style` sees all styles | Use `getComputedStyle(el)` | An empty string |
| `classList.add(".paid")` | Class names need dots | Dots are for selectors | No CSS matches |
| `classList.add("paid urgent")` | One string, two classes | Pass two arguments | `InvalidCharacterError` |
| Editing `className` by hand | Strings are fine | Use `classList` | Duplicates or broken names |
| `toggle("open")` to match data | It knows the state | Use `toggle("open", isOpen)` | It drifts out of step |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `el.style.backgroundColor = "#2563eb"` | set one inline style, with the CSS name in camelCase |
| `el.style.width = ""` | clear one inline style |
| `el.style.setProperty("--fill", "75%")` | set a style by its CSS name, including custom properties |
| `el.style.removeProperty("--fill")` | remove a style set by its CSS name |
| `getComputedStyle(el).color` | the final style the browser applied, from every source |
| `el.classList` | the element's classes, as a live `DOMTokenList` |
| `el.classList.add("paid", "urgent")` | add one or more classes, never twice |
| `el.classList.remove("urgent")` | remove one or more classes, ignoring missing ones |
| `el.classList.toggle("open")` | flip a class, and return whether it is now present |
| `el.classList.toggle("open", isOpen)` | add or remove the class to match a true or false value |
| `el.classList.contains("paid")` | `true` if the class is present |
| `el.classList.replace("packing", "shipped")` | swap one class for another in the same position |

</div>

## Exercises

## What to Remember

- JavaScript switches classes; CSS decides the look.
- Inline styles need units and only show inline values.
- `classList` works on whole tokens, safely.

Next: **DOM Events and Forms**. Respond to clicks, typing and form submissions, and check what users enter.
