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.
<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
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.
<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().
<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 when | Use 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 |