JavaScript DOM Changing CSS
JavaScript can change how elements look by setting inline styles directly or, better, by toggling CSS classes.
Setting styles with the style property
Every element has a style property that lets you set inline CSS from JavaScript. Each CSS property is available in camelCase, so background-color becomes backgroundColor and font-size becomes fontSize. Values are always assigned as strings, including their units.
Changing inline styles
<!DOCTYPE html>
<html>
<body>
<div id="banner">Welcome!</div>
<script>
const banner = document.getElementById("banner");
banner.style.backgroundColor = "navy";
banner.style.color = "white";
banner.style.padding = "16px";
banner.style.fontSize = "1.25rem";
</script>
</body>
</html>Working with classes
Setting styles one at a time is fine for a single tweak, but the cleaner approach for anything reusable is to define the look in a CSS class and switch that class on and off with classList. This keeps your styling in the stylesheet and your logic in JavaScript.
Toggling classes with classList
<!DOCTYPE html>
<html>
<body>
<nav id="menu" class="hidden">Menu</nav>
<script>
const menu = document.querySelector("#menu");
// Add, remove, and toggle a class
menu.classList.add("open");
menu.classList.remove("hidden");
menu.classList.toggle("active");
// Check whether a class is present
if (menu.classList.contains("open")) {
console.log("The menu is open.");
}
</script>
</body>
</html>classList methods
Inline styles versus classes
- Use the style property for a small, one-off change or a value computed at runtime
- Use classes when the same look is reused or when several properties change together
- Classes keep design decisions in the stylesheet where they are easier to maintain
- Reading element.style only returns inline styles, not rules from a stylesheet
To read the styles that are actually applied to an element, including those from your stylesheet, use window.getComputedStyle. It returns the final, resolved values the browser is using to paint the element.
Reading the computed style
<!DOCTYPE html>
<html>
<body>
<div id="box">Sample box</div>
<script>
const box = document.getElementById("box");
const styles = window.getComputedStyle(box);
console.log(styles.color); // e.g. "rgb(0, 0, 0)"
console.log(styles.fontSize); // e.g. "16px"
</script>
</body>
</html>