The output of the above code is shown below:
We will discuss one by one.
The function which is used for adding one or more classes to the CSS element.
Below example shows how to add a class using classList.add() method:
In the code, when the user clicks on the button, the new class get added with the existing classes. The output after clicking on the button is shown below:
The remove() function is used for removing the existing classes from the elements.
Below example shows how to remove one or more class using classlist.remove() method:
In the above code, when the user clicks on the button, the particular specified class gets removed from the existing CSS classes. The output after clicking on the button is shown below:
The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.
Below is an example that will make us understand how to make use of the toggle() method to add or remove classes.
In the code, when the user clicks on the button, the class will get added or removed from the CSS classes. The output after clicking on the button is shown below:
The contains() method is used to check whether the specified class exist in the CSS classes and with respect to it, it returns the Boolean value as true or false.
Below is an example that shows how to search for a class if it exist or not using the contains() method:
In the above code, it is seen that when the user clicks on the button, then it checks for the specified class if present in the CSS classes. If it is present, a Boolean value as true will be returned. Else, it will return false. The output of the above code after clicking on the button is shown below:
The replace() method is used for replacing an existing class with a new one. It does not mean that the class is removed from the elements but the properties of the existing class get replaced with the properties of the new class.
Below is an example through which we will understand that how we can replace an existing class with a new class:
In the above code, when the user clicks on the button, the existing class properties get replaced with the new class properties. The output after clicking on the button is shown below:
The item() function is used to return the name of the class which is present at the specified index value.
Below is an example that will make us understand how to use item() method to return the value:
In the code, when the user clicks on the button, the class present on the specified index will get displayed. After clicking on the button, we get the specified index class value, as shown below:
These are some of the methods of the classList DOM object and all about classList.