JavaScript Styles and Classes
Control an element's appearance from JavaScript: className and classList (add, remove, toggle, contains, replace), the style property and cssText.
Introduction
There are two ways to change how an element looks from JavaScript:
- Add or remove a CSS class — the styling lives in a stylesheet, and JavaScript only flips the class on or off. This is the preferred approach.
- Set an inline style directly on the element with the
styleproperty — useful when the value is computed at runtime (for example, a position that depends on the mouse).
This chapter covers both: the className and classList APIs for working with classes, the style property and cssText for inline styles, and getComputedStyle for reading the final styles a browser actually applied. For the bigger picture of CSS and the DOM, see Working with Styles in the DOM.
The style property
Direct Style Manipulation
The style property is an object whose keys are the element's inline CSS properties. To modify the style of an element directly through JavaScript, assign to one of those keys. Here's an example of changing the background color and font size of a paragraph:
<!-- snippet: html-result -->
<style>
#myParagraph {
color: white; /* Ensures text is readable on a blue background */
}
</style>
<div id="myParagraph">This is a paragraph.</div>
<script>
document.getElementById("myParagraph").style.backgroundColor = "blue";
document.getElementById("myParagraph").style.fontSize = "16px";
</script>Note the property names: CSS uses hyphens (background-color, font-size), but the style object uses camelCase (backgroundColor, fontSize). Multi-word properties always follow this rule, and prefixed properties keep the leading dash as a capital letter (-moz-border-radius becomes MozBorderRadius). Values are always strings, and numeric CSS values must include their unit — el.style.fontSize = "16px", not 16.
Setting el.style.backgroundColor writes to the element's style="..." attribute, so it only affects that one element and overrides stylesheet rules (it has the same weight as an author inline style). To remove an inline value, assign an empty string: el.style.fontSize = "".
This method offers straightforward control but may be cumbersome for multiple style changes.
Using style.cssText
For applying multiple style changes efficiently, use style.cssText:
<!-- snippet: html-result -->
<style>
#myParagraph {
padding: 5px;
width: 200px;
text-align: center;
}
</style>
<div id="myParagraph">Another paragraph.</div>
<script>
document.getElementById("myParagraph").style.cssText = "background-color: blue; font-size: 16px; border: 1px solid black";
</script>This approach consolidates style changes into a single operation. Be aware that cssText replaces the entire inline style, wiping out any properties already set on the element. Use it when you want a clean slate; use individual style.* assignments when you want to change one property and leave the rest untouched.
Reading styles with getComputedStyle
The style property only reflects inline styles — values set in the style attribute or via JavaScript. It returns an empty string for anything coming from a stylesheet. To read the final, resolved value the browser actually rendered (from every stylesheet, inline rule, and inherited value), use getComputedStyle:
<!-- snippet: html-result -->
<style>
#box { width: 10em; padding: 5px; }
</style>
<div id="box">Measure me</div>
<script>
const box = document.getElementById("box");
const styles = getComputedStyle(box);
// Computed values are resolved to absolute units (px), not the "10em" we wrote:
console.log(styles.width); // "160px" (10em at the default 16px font size)
console.log(styles.padding); // "5px"
</script>A few rules to remember:
- The returned object is read-only — assigning to it has no effect; use
element.styleto change styles. - Values are resolved: lengths come back in pixels, colors in
rgb(...)form. - Always read a specific property (
getComputedStyle(el).marginTop), and prefer the longhand name — some shorthand properties (margin,padding) are returned inconsistently across browsers.
className vs classList
There are two ways to read and write an element's classes:
element.classNameis a single string holding the wholeclassattribute. Assigning to it replaces every class at once:el.className = "active warning". Handy for setting all classes from scratch, clumsy for changing just one.element.classListis a special object with methods for working with individual classes —add,remove,toggle,contains, andreplace. This is what you'll reach for most of the time, because it lets you change one class without disturbing the others.
The methods are:
| Method | What it does |
|---|---|
classList.add("a", "b") | Adds one or more classes (no-op if already present) |
classList.remove("a", "b") | Removes one or more classes (no-op if absent) |
classList.toggle("a") | Adds the class if missing, removes it if present |
classList.contains("a") | Returns true/false — does the element have this class? |
classList.replace("old", "new") | Swaps one class name for another |
(The property is named className, not class, because class is a reserved word in JavaScript — see Attributes and Properties.)
Adding and Removing Classes
Using the classList API enhances the ease of class manipulation.
Adding a Class
<!-- snippet: html-result -->
<style>
.new-class {
font-weight: bold;
color: green;
}
</style>
<div id="myDiv">Class manipulation</div>
<script>
document.getElementById("myDiv").classList.add("new-class");
</script>Removing a Class
<!-- snippet: html-result -->
<style>
.existing-class {
text-decoration: underline;
color: red;
}
</style>
<div id="myDiv" class="existing-class">Another manipulation example</div>
<script>
document.getElementById("myDiv").classList.remove("existing-class");
</script>Toggling a Class
Toggle functionality is effective for switching styles such as themes:
<!-- snippet: html-result -->
<style>
.dark-mode {
background-color: black;
color: white;
}
</style>
<button id="toggleButton">Toggle Dark Mode</button>
<script>
document.getElementById("toggleButton").addEventListener("click", function() {
document.body.classList.toggle("dark-mode");
});
</script>Handling Multiple Classes
Manage several classes simultaneously:
<!-- snippet: html-result -->
<style>
.first-class { background-color: yellow; }
.second-class { border: 2px dashed blue; }
.third-class { display: none; }
.fourth-class { font-size: 14px; }
</style>
<div id="myDiv">Multiple class handling</div>
<script>
document.getElementById("myDiv").classList.add("first-class", "second-class");
document.getElementById("myDiv").classList.remove("third-class", "fourth-class");
</script>Checking and Replacing Classes
Use contains to branch on whether a class is present, and replace to swap one class for another in a single call:
const el = document.getElementById("myDiv");
el.classList.contains("active"); // false
el.classList.add("active");
el.classList.contains("active"); // true
// Swap "active" for "disabled" (returns true if the swap happened):
el.classList.replace("active", "disabled"); // true
el.classList.contains("active"); // false
el.classList.contains("disabled"); // truetoggle also accepts an optional second argument that forces the result: classList.toggle("open", isOpen) adds the class when isOpen is true and removes it when false, which is convenient when the desired state is already in a boolean.
Best Practices: Classes vs. Inline Styles
Prefer classes over inline styles. Keep the styling in your CSS and let JavaScript only toggle a class name. This keeps presentation and behavior separate, so designers can change the look without touching scripts, the same class can be reused across many elements, and your styles stay in one searchable place.
Reach for element.style only when a value genuinely has to be computed at runtime — an element's position that follows the mouse, a width derived from data, a color picked from user input. These can't live in a static stylesheet, so an inline value is the right tool.
When a class change should animate rather than snap, define a CSS transition on the property and let toggling the class drive it. The browser handles the animation on its own optimized path, which is smoother than stepping values from JavaScript. See CSS Animations for the details.
Conclusion
Use classList (add, remove, toggle, contains, replace) to manage classes and let your stylesheet do the visual work; fall back to element.style only for values that must be computed at runtime; and read final, applied values with getComputedStyle — remembering it's read-only. Keeping styling in CSS and letting JavaScript flip classes leads to code that's easier to maintain and faster to render.