7) The Document Object Model Lesson

Change CSS Styles With JavaScript

22 min to complete · By Ian Currie

There are hundreds of ways you can change the elements in the DOM. One of the particularly fun things to change are things that make the look of the page change.

In this lesson, you'll learn how to change the style of DOM elements.

CSS Inline Style vs CSS Classes

Before diving into changing the style of DOM elements, it's important to understand the difference between inline styles and classes.

You can change the style of DOM elements in two ways. You can either change the inline style of the element, or you can change the class of the element.

An inline style is applied to the element in the HTML. For example:

<button id="mainBtn" style="color: red;">Lorem Ipsum</button>

Applying a style with a class looks like this:

<style>
  .red {
    color: red;
  }
</style>
<button class="red" id="mainBtn">Lorem Ipsum</button>

In both examples, the final result is the same. The button will be red. However, the way you get there is different. The difference between these mainly comes down to the precedence of styles. Inline styles have a higher precedence than class styles. This means that if you have a class style and an inline style that are both trying to change the same property, the inline style will win:

<style>
  .red {
    color: red;
  }
</style>
<button class="red" id="mainBtn" style="color: blue;">Lorem Ipsum</button>

This button will be blue, because the inline style has a higher precedence than the class style.

Changing the Inline Style of DOM Elements

The most straightforward way to change the style of an element is to change the inline style of the element. You can do this with the .style property of the element. This property is an object that contains all of the styles of the element. You can change any of the styles by changing the property of the style object. For example:

let btn = document.getElementById("mainBtn");
btn.style.color = "red";

This will change the color of the button to red. You can also change multiple styles at once:

let btn = document.getElementById("mainBtn");
btn.style.color = "red";
btn.style.backgroundColor = "blue";

This will change the color of the button to red and the background color to blue.

Colorful illustration of a light bulb

Note: Any CSS property is available as a property of the style object. If the property has a dash, like background-color, it is camel-cased in JavaScript: backgroundColor.

For example:

CSS JavaScript
background-color backgroundColor
font-size fontSize
border-radius borderRadius

When you change the inline style of an element by modifying the .style property, you are changing the style of that element directly. This is the style that is applied to the element in the HTML. If you open the developer tools in your browser and inspect the element, you will see the inline style that you have applied.

Keep in mind that inline styles are best for a few changes, or changes that you don't need to reuse widely across the page. If you need to change a lot of styles at once, it can be easier to change the class of the element instead of changing the inline style of every single element.

Changing the Class of DOM Elements

Another way to change the style of an element is to change the class of the element. If you need to change a lot of styles at once, it can be easier to change the class of the element instead of changing the inline style of every single element.

It also allows you to have complex styles defined in CSS class, that you can then apply to an element with just one operation.

The best way to change the class of an element is to use the .classList property of the element. This property is an object that has a bunch of methods for manipulating the class of the element.

When you change the class of an element by using a .classList method, you are changing the class of that element directly. This is the class that is applied to the element in the HTML. If you open the developer tools in your browser and inspect the element, you will see the changes applied there.

The .classList property itself is a DOMTokenList object. An array-like object that contains all of the classes of the element. For example, if a button has the classes red and big, the .classList property will look like this:

let btn = document.getElementById("mainBtn");
btn.classList; // DOMTokenList ["red", "big", value: "red big"]

As you can see the DOMTokenList has the classes red and big as string elements of an array-like structure, that can be references with square bracket notation. It also has a value property that contains all of the classes as a string, this is the underlying string that is what is on the actual HTML.

Here are the methods you'll cover:

Method Description Example
.add() Adds a class to an element. Does nothing if the class already exists. btn.classList.add("red");
.remove() Removes a class from an element. Does nothing if the class does not exist. btn.classList.remove("red");
.toggle() Toggles a class on and off of an element. Can also take a second boolean argument to force add (true) or remove (false). btn.classList.toggle("red");
btn.classList.toggle("red", true);
.replace() Replaces an existing class with another class. btn.classList.replace("red", "blue");
.contains() Checks if an element has a certain class, returning true or false. btn.classList.contains("red");

In all the examples that follow, you'll start off with a button that has the following HTML:

<button id="mainBtn" class="red big">Lorem Ipsum</button>

Using the .add() Method of the .classList Property

To add a class to an element, you can use the .add() method of the .classList property. For example:

let btn = document.getElementById("mainBtn");
btn.classList.add("rounded");

This will add the class rounded to the button. If the rounded class is already on the button, this will do nothing.

That will result in this HTML:

<button id="mainBtn" class="red big">Lorem Ipsum</button>
<!-- Becomes -->
<button id="mainBtn" class="red big rounded">Lorem Ipsum</button>

Using the .remove() Method of the .classList Property

You can also remove a class from an element with the .remove() method of the .classList property:

let btn = document.getElementById("mainBtn");
btn.classList.remove("red");

This will remove the class red from the button. If the red class is not on the button, this will do nothing.

That will result in this HTML:

<button id="mainBtn" class="red big">Lorem Ipsum</button>
<!-- Becomes -->
<button id="mainBtn" class="big">Lorem Ipsum</button>

Using the .toggle() Method of the .classList Property

You can also toggle a class on and off with the .toggle() method of the .classList property:

let btn = document.getElementById("mainBtn");
btn.classList.toggle("red");

This will toggle the class red on and off of the button.

That will result in this HTML:

<button id="mainBtn" class="red big">Lorem Ipsum</button>
<!-- Becomes -->
<button id="mainBtn" class="big">Lorem Ipsum</button>

The .toggle() method also has a second argument that you can use to force the class to be added or removed:

let btn = document.getElementById("mainBtn");
btn.classList.toggle("red", true);

So if the class red is not on the button, this will add it. If the class red is already on the button, this will do nothing.

That will result in this HTML:

<button id="mainBtn" class="red big">Lorem Ipsum</button>
<!-- Becomes -->
<button id="mainBtn" class="red big">Lorem Ipsum</button>

Using the .replace() Method of the .classList Property

You can also replace a class with another class with the .replace() method of the .classList property:

let btn = document.getElementById("mainBtn");
btn.classList.replace("red", "blue");

This will replace the class red with the class blue on the button.

That will result in this HTML:

<button id="mainBtn" class="red big">Lorem Ipsum</button>
<!-- Becomes -->
<button id="mainBtn" class="blue big">Lorem Ipsum</button>

Using the .contains() Method of the .classList Property

Sometimes you want to check if an element has a certain class. You can do this with the .contains() method of the .classList property:

let btn = document.getElementById("mainBtn");
btn.classList.contains("red"); // true

This will return true if the button has the class red and false if it does not.

The .className Property

You can also change the class of an element by changing the .className property of the element. This property is a string that contains all of the classes of the element.

This method is not recommended because it's more error prone than using the .classList property. However, it's still worth knowing about because you may see it in other people's code, as it was the only way to change the class of an element in older browsers.

For example:

let btn = document.getElementById("mainBtn");
btn.className = "rounded";

This will change the class of the button to rounded. Note that this will overwrite any existing classes on the element.

That will result in this HTML:

<button id="mainBtn" class="red big">Lorem Ipsum</button>
<!-- Becomes -->
<button id="mainBtn" class="rounded">Lorem Ipsum</button>

So if you wanted to add a class, you would need to include all of the classes in the string:

let btn = document.getElementById("mainBtn");
btn.className = "red big rounded";
// or
btn.className += " rounded";

This will change the class of the button to red big rounded.

<button id="mainBtn" class="red big">Lorem Ipsum</button>
<!-- Becomes -->
<button id="mainBtn" class="red big rounded">Lorem Ipsum</button>

So, you can manage classes with the .className property, but that means you have to manage all the operations as string operations. The .classList property abstracts all that string handling away, and provides a much cleaner interface to manage classes.

Using JavaScript to Trigger a CSS Transition

A fun way to practice your new found skills is to use JavaScript to trigger a CSS transition.

Take this HTML:

<style>
  .box {
    width: 100px;
    height: 100px;
    background-color: red;
    transition: all 5s; /* 5 second transition */
  }

  .big-box {
    width: 200px;
    height: 200px;
    background-color: blue;
  }
</style>
<div class="box"></div>

Which will create a red box on the page. You can use JavaScript to add the big-box class to the box, which will trigger the transition:

setTimeout(() => {
  document.querySelector(".box").classList.add("big-box");
}, 1000);

In this code, you use the .querySelector() method to select the box. You then use the .classList.add() method to add the big-box class to the box.

You've got this operation inside an arrow function that is passed to the .setTimeout() method which will run the function after one second so you can see it in action.

You should see the red box gradually grow to a blue box over the course of 5 seconds. Cool!

Colorful illustration of a light bulb

Since we apply the big-box class to the box, it ends up being a class applied after the box class. This means that the big-box class will override the conflicting elements in the box class. It still retains other properties set in the box class, like the transition property.

Try it out!

Other Ways to Change Styles

As with all things JavaScript, there are many ways to go about the same task. Here are some lesser known techniques for changing styles.

Adding Style Rules

You can even insert new style rules into the page with JavaScript with the .insertRule() method of the .styleSheets object. This is a bit more advanced, but it's worth knowing about. For example:

document.styleSheets[0].insertRule(
  "p { color: red; }",
  document.styleSheets[0].cssRules.length
);

This will insert a new style rule into the page that will make all paragraphs red.

Changing CSS Variables

Another nifty way to manage styles is to change CSS custom properties with JavaScript also known as CSS variables. CSS custom properties are very useful to manage styles in a complex application. Typically they are set on a root element, like the :root pseudo-class. For example:

:root {
  --main-color: red;
}

.box {
  background-color: var(--main-color);
  height: 100px;
  width: 100px;
}

Here you set the --main-color variable to red, and then used that variable in the background-color property of the .box class. You can reuse that variable anywhere in your CSS. Really useful!

You can then change the value of that variable with JavaScript:

document.documentElement.style.setProperty("--main-color", "blue");

This will change the value of the --main-color variable to blue, which will change the background color of the box to blue.

This is just another way to compose your dynamic styles with CSS and JavaScript.

Summary: How to Manipulate the DOM With Javascript

You've taken the exciting first steps towards manipulating the Document Object Model (DOM) to enhance the visual aspects of a webpage. In this lesson you've:

  • Differentiated between inline styles and classes. Inline styles are written directly in the HTML and take precedence over CSS class styles.
  • Grasped how to modify the inline style of DOM elements using the .style property, perfect for adjusting individual style properties.
  • You’ve seen that camelCase is used in JavaScript for CSS properties that normally contain hyphens (e.g., backgroundColor instead of background-color).
  • Become familiar with the .classList property and its methods such as .add(), .remove(), and .toggle(), which are great tools for working with multiple classes.
  • Also understood why directly changing the .className property isn't recommended compared to .classList due to potential mishandling of existing classes.
  • Learned how to use JavaScript to trigger CSS transitions, adding dynamic visual effects to elements on your page.

Remember, while inline styles can be quick and direct, classes provide a more scalable and maintainable way to manage styling, especially for complex or reusable styles. Enjoy testing these methods to find creative ways to bring your web pages to life!