Changing DOM Styles
Table of Contents + −
In the previous lesson, we learned how to change the text and HTML inside an element. Now let’s change how an element looks, by updating its styles from JavaScript.
🎨 The style Property
Every element has a style property that lets you set inline CSS directly. You read or write each CSS rule as a property on style.
The example below selects a heading and turns its text red.
const title = document.querySelector("#title");
title.style.color = "red";Let’s walk through what each line does:
- The first line selects the element with
id="title"and stores it intitle. - The second line sets that element’s inline
colortored, exactly as if you had writtenstyle="color: red"in the HTML.
The important detail is the name. In CSS you write background-color, but in JavaScript you write backgroundColor. Property names that contain a hyphen become camelCase, with the hyphen removed and the next letter capitalized.
| CSS Name | JavaScript Name |
color | style.color |
background-color | style.backgroundColor |
font-size | style.fontSize |
text-align | style.textAlign |
Here is a small example that sets a few styles at once.
const box = document.querySelector("#box");
box.style.backgroundColor = "lightblue";box.style.fontSize = "20px";box.style.padding = "10px";Let’s read this one line by line:
- The first line grabs the element with
id="box"and saves it inbox. - The next line sets its
background-colortolightblueusing the camelCase namebackgroundColor. - The line after that sets its
font-sizeto20pxthroughfontSize. - The last line sets
paddingto10px. Each value is a string, just like you would write it in CSS.
🧱 The classList Property
Setting one style at a time works, but it spreads styling across your JavaScript. The cleaner approach is to keep the look in a CSS class and switch that class on and off from JavaScript. The classList property gives you methods to do exactly that.
| Method | What It Does | Example |
add | Adds a class to the element | el.classList.add("active") |
remove | Removes a class from the element | el.classList.remove("active") |
toggle | Adds the class if missing, removes it if present | el.classList.toggle("active") |
contains | Returns true if the class is present | el.classList.contains("active") |
First you define the look in CSS:
.dark { background-color: black; color: white;}This CSS rule bundles two style rules under one name:
- The
.darkselector targets any element that has thedarkclass. - Inside it,
background-color: blackandcolor: whiteset a dark background with light text. Any element you give this class gets both rules at once.
Then you switch that class with JavaScript:
const page = document.querySelector("#page");
page.classList.add("dark"); // turns the look onpage.classList.remove("dark"); // turns the look offconsole.log(page.classList.contains("dark")); // falseLet’s follow each line:
- The first line selects the element with
id="page"and stores it inpage. classList.add("dark")puts thedarkclass on the element, so the CSS rule above takes effect.classList.remove("dark")takes that class back off, undoing the look.classList.contains("dark")checks whether the class is still there. Since we just removed it, this logsfalse.
🌗 Why classList Is Better
Toggling a class keeps all your styling in the CSS file, where it belongs. Your JavaScript only decides when a look applies, not what that look is. This means you can change the design later by editing CSS, without touching your code, and one class can carry many style rules at once.
Keep styling in CSS
Reach for classList whenever you can, and save style for rare one-off
values you have to calculate at runtime, like a position in pixels.
🌓 Practical Example: A Dark Mode Toggle
The toggle method shines when you want a button that switches a look on and off. Each click flips the dark class on the page.
const button = document.querySelector("#themeButton");const page = document.querySelector("#page");
button.addEventListener("click", () => { page.classList.toggle("dark"); // ✅ on, off, on, off...});Let’s break down what happens here:
- The first two lines grab the button and the page element and store each in its own variable.
button.addEventListener("click", ...)runs the function inside it every time the button is clicked.- On each click,
page.classList.toggle("dark")adds thedarkclass if it is missing and removes it if it is present.
The browser adds the dark class on the first click and removes it on the next. You never have to track the current state yourself.
⚠️ Common Mistakes to Avoid
| Mistake | Problem | Solution |
Using hyphenated CSS names in style | el.style.background-color is invalid JavaScript | Use camelCase: el.style.backgroundColor |
Overwriting className | el.className = "dark" erases every existing class | Use el.classList.add("dark") instead |
| Putting all styling inline | Styles scatter through your code and are hard to change | Define a class in CSS and toggle it |
🔧 Try It Yourself!
- Select an element and change its
backgroundColorandfontSizewith thestyleproperty. - Add a
.highlightclass in your CSS, then turn it on withclassList.add. - Add a button that calls
classList.toggle("highlight")on each click. - Use
classList.containsto print whether the class is currently applied.
🧩 What You’ve Learned
- ✅
element.style.propertysets inline CSS, using camelCase names likebackgroundColor - ✅
classListadds, removes, toggles, and checks CSS classes - ✅
toggleflips a class on and off without tracking state - ✅ Switching classes keeps your styling in CSS where it is easy to change
- ✅ Avoid overwriting
classNameand avoid scattering styles inline
🚀 What’s Next?
Now that you can restyle elements, we will learn how to build brand-new ones from scratch. Let’s continue to Creating Elements.