There are a bunch of helpful methods to add, remove, or toggle a class. We are going to explore some of them in this tutorial.
In the following example, we have a bunch of button elements and a div element with a text “Hello World”. Upon click of each button element, we are going to perform various class-related actions. Please have a look over the code example and the steps given below.
HTML & CSS
We have 2 elements in the HTML file (div and button). The div element with a class of controls is just a wrapper for the button elements.
We also have one div element with the text “Hello World”. All class-related actions will be performed on this div element.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected all the button elements and the div element using the document.querySelector() method and stored them in the add, remove, toggle, check, addAll, removeAll, and hello variables respectively.
We have attached the click event listener to all the button elements.
In the event handler function of add button, we are adding the bg class to the div element using the add() method.
In the event handler function of the remove button, we are removing the bg class from the div element using the remove() method.
In the event handler function of the toggle button, we are toggling the bg class of the div element using the toggle() method.
Check if Class is Present
In the event handler function of the check button, we are using contains method of classList to verify whether the bg class is present in the list of the applied classes to the div element. This method returns a Boolean value.
We are displaying that Boolean value in the div element using the innerText property.
Adding Multiple Classes
In the event handler function of the addAll button, we are adding bg and bd classes to the div element using add() method.
Removing Multiple Classes
In the event handler function of the removeAll button, we are removing bg, bd, and hello classes from the div element using the remove() method.