Skip to content

JavaScript Tutorial The DOM

Changing Styles with JavaScript

Lesson 105 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Sometimes you need to set a style from code, for example a width that is calculated, or a color the user picked.

The style property

element.style lets you set inline styles. Property names are written in camelCase.

index.html
HTML
<p id="note">Styled by JavaScript</p>
<script>
  const note = document.querySelector("#note");

  note.style.color = "white";
  note.style.backgroundColor = "#d94a00";   // background-color becomes backgroundColor
  note.style.padding = "12px";
  note.style.fontSize = "20px";

  console.log(note.style.padding); // → 12px
</script>

Values are strings, with units: "12px", not 12.

Removing an inline style

script.js
JS
note.style.color = "";            // removes that inline value
note.style.removeProperty("padding");

CSS custom properties

Use setProperty() for CSS variables (the ones that start with --). This is a very clean way to connect JavaScript values to your stylesheet.

index.html
HTML
<style>
  .bar { height: 14px; background: #1a5276; width: var(--progress, 0%); transition: width 0.3s; }
  .track { background: #ddd; width: 240px; }
</style>
<div class="track"><div id="bar" class="bar"></div></div>
<button id="more">+25%</button>
<script>
  let progress = 0;
  const bar = document.querySelector("#bar");
  document.querySelector("#more").addEventListener("click", () => {
    progress = Math.min(100, progress + 25);
    bar.style.setProperty("--progress", progress + "%");
  });
</script>

Reading the real style

element.style only knows about inline styles. To read what is actually applied (from stylesheets too), use getComputedStyle().

index.html
HTML
<style>
  p { color: rgb(26, 82, 118); font-size: 18px; }
</style>
<p id="text">Hello</p>
<script>
  const text = document.querySelector("#text");

  console.log(JSON.stringify(text.style.color));       // → ""   (no inline style)
  console.log(getComputedStyle(text).color);              // → rgb(26, 82, 118)
  console.log(getComputedStyle(text).fontSize);           // → 18px
</script>

Inline styles vs classes

Use inline style whenUse a class when
The value is calculated (a position, a width)You are switching between known looks
The user picked it (a color)Several properties change together
info
Inline styles are strong
Inline styles override most stylesheet rules (see CSS Specificity), which can make them hard to override later. That is another reason to prefer classes.