Newsletter

How to change CSS classes in JavaScript with classList

How to change the CSS classes on an HTML element with the JavaScript classList object: add, check, remove and toggle a class while manipulating the DOM.

How to change CSS classes in JavaScript with classList

This article shows you how to change CSS classes with the JavaScript classList object in your DOM manipulation project. The classList object lets you adjust the CSS classes assigned to an HTML element.

html
<!DOCTYPE html>
<html>
<head>
  <title>Mon titre</title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
	<style type="text/css">
	  .colorText {
        color: purple;
      }

.boldText {
        font-weight: bold;
      }

.bigText {
        font-size: 35px;
      }
	</style>
</head>
<body>
    <p id="myText">
      Hello World!
    </p>
</body>
</html>

Now let us restyle that text with the classList property and apply your CSS classes.

Using the classList .add() and .contains() methods

Create an index.js file, get a reference to your paragraph element, and call the classList.add() method:

index.js

javascript
const myText = document.getElementById('myText');

myText.classList.add('colorText');

The built-in classList.add() method applies a class to your HTML element. Here, the text inside the paragraph element now appears in purple.

You can also check whether the CSS class exists on your paragraph element with the classList.contains() method, which returns a boolean:

javascript
const myText = document.getElementById('myText');

console.log(myText.classList.contains('colorText')); // true

Since the colorText CSS class does exist on your paragraph element, the call returns true.

Using the classList .item() and .remove() methods

In your index.js file, add a few more CSS classes to your paragraph element:

index.js

javascript
const myText = document.getElementById('myText');

myText.classList.add('boldText');
myText.classList.add('bigText');
console.log(myText.classList); // ['colorText', 'boldText', 'bigText'];

The classList property stores every extra class in an array. Log myText.classList to the console and you get an array holding your CSS classes.

To read the class sitting at a given index in that array, call the classList.item() method:

javascript
const myText = document.getElementById('myText');

myText.classList.item('boldText'); // 2

To remove a CSS class, use the classList.remove() method:

javascript
const myText = document.getElementById('myText') ;

myText.classList.remove('bigText') ;
console.log(myText.classList) ; // ['colorText', 'boldText'];

Log myText.classList again and the class you removed is gone from the array, and no longer applies to your paragraph element.

Now that you can add, check and remove CSS classes, let us look at what the other classList methods bring.

Working with the classList .toggle() method

Instead of calling classList.add() and classList.remove() side by side, you can use the classList.toggle() method:

To do that, wire up an event listener on a button in your index.js file:

index.js

javascript
textButton.addEventListener('click', () => {
  myText.classList.toggle('newFont');
});

On every click, classList.toggle() adds the CSS class if it is not in the classList array and returns true. If the CSS class is already there, the method removes it and returns false.

javascript
const anotherClass = myText.classList.toggle('newSize');

console.log(anotherClass); // true --> the class has been added

You can also pass a boolean as an optional second argument to classList.toggle(). The class is then added or removed depending on how that second argument evaluates:

javascript
const bool = false;

let firstToggle = myText.classList.toggle('newSize', bool);
console.log(firstToggle);
// false, 'newFont' already exists and will be removed from the classList array

let secondToggle = shadesEl.classList.toggle('newColor', !bool);
console.log(secondToggle);
// true, 'newColor' does not exist and the class will be added.

The classList.toggle() method adds and removes CSS classes whether or not they are already in your array, and does it in fewer lines of code.

Conclusion

The classList property is a faster, richer way of changing your HTML elements and their CSS classes in JavaScript.

To go further, read the article on how to change the DOM in JavaScript.

CSSJavaScript

Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.