Categories
JavaScript Answers

How to add and remove multiple CSS classes to an element with JavaScript?

Spread the love

You can add and remove multiple CSS classes to an element using JavaScript by manipulating the classList property of the element.

The classList property provides methods to add, remove, toggle, and check for the presence of CSS classes on an element.

Here’s how you can add and remove multiple CSS classes:

// Get the element you want to add/remove classes to
var element = document.getElementById('myElement');

// Add multiple classes to the element
element.classList.add('class1', 'class2', 'class3');

// Remove multiple classes from the element
element.classList.remove('class1', 'class2', 'class3');

In this example, replace 'myElement' with the ID of the element to which you want to add or remove classes. Replace 'class1', 'class2', and 'class3' with the names of the classes you want to add or remove.

You can also use other methods provided by the classList property, such as toggle() to toggle the presence of a class, or contains() to check if a class is present on the element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *