Tutorial

How To Modify CSS Classes in JavaScript

Updated on October 13, 2020
authorauthor

Alligator.io and Natalia Vargas-Caba

How To Modify CSS Classes in JavaScript

Introduction

In this tutorial, you will learn how to modify CSS classes using the JavaScript classList object for your DOM Manipulation project. The classList object allows you to adjust CSS classes that are assigned to an HTML element.

Prerequisites

Starting Your Project

Create an index.html file, and include a style tag with CSS classes and a paragraph element with an id:

[label index.html] 
<style>
  .colorText {
    color: purple;
  }

  .boldText {
    font-weight: bold;
  }

  .bigText {
    font-size: 35px;
  }
</style>

<p id="myText">
  Hello World! 
</p>

Let’s now modify your text with the classList property and apply your CSS classes.

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

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

[label index.js] 
const myText = document.getElementById('myText');

myText.classList.add('colorText');

The built-in classList.add() method applies a class to your HTML element. In this case, your text in the paragraph element will now appear purple.

You can also check if the CSS class exists in your paragraph element using the classList.contains() method to return a boolean:

[label index.js] 
const myText = document.getElementById('myText');

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

Since the CSS class colorText exists in your paragraph element, your call returns true.

Applying the .item() and .remove() classList Methods

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

index.js
const myText = document.getElementById('myText');

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

The classList property stores each additional class in an array. If you console out myText.classList, an array with your CSS classes will output.

To check on the specified index of each CSS class in the array, call on the classList.item() method:

index.js
const myText = document.getElementById('myText');

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

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

[label index.js] 
const myText = document.getElementById('myText');

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

Once you console out myText.classList, the CSS class you removed does not appear in the array and will not apply to your paragraph element.

Now that you can add, check, and remove CSS classes, let’s explore how to amplify other classList methods.

Handling the classList .toggle() Method

Instead of calling classList.add() and classList.remove() simultaneously, you can utilize the classList.toggle() method:

To achieve this, implement an event listener on a button in your index.js file:

[label index.js] 
textButton.addEventListener('click', () => {
  myText.classList.toggle('newFont');
});

With each click, classList.toggle() will add the CSS class if it does not exist in the classList array and return true. If the CSS class exists, the method will remove the class and return false.

[label index.js] 
const anotherClass = myText.classList.toggle('newSize');

console.log(anotherClass); // true --> class was added

You can also add a boolean as an optional second argument in the classList.toggle() method. This will either add or remove the CSS class, depending on how the second argument evaluates:

index.js
const bool = false; 

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

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

The classList.toggle() method supports adding and removing CSS classes whether they exist or not in your array with shorter lines of code.

Conclusion

The classList property allows greater performance and functionality to alter your HTML elements and their CSS classes within JavaScript.

For additional reading, check out the article How To Modify Attributes, Classes, and Styles in the DOM and the ebook Understanding the DOM — Document Object Model.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Alligator.io

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel