Add Class Name
Here is how to add a new class name ‘MyClass’ to the element using add() function, called on classList property of the element.
Here is how to add the same class using jQuery.
Remove Class Name
Here is how to remove class name MyClass for the element.
You can remove class names using jQuery’s removeClass() function.
Replace Class Name
You can also completely overwrite an element’s existing classes with a new value, using .className property of the element.
document.getElementById("MyElement").className = "MyClass";
Please note, this will completely remove all existing class names of the element and replace it with the new value you have specified.
You can also use this property to add class names. Here is an example to add new class name to your element.
document.getElementById("MyElement").className += " MyClass1";
Check if Class Name Exists
Sometimes you may also need to check if a specific class name exists for an element. You can do so using the contains() function on classList property. Here is the code to check if your element has MyClass class name.
if ( document.getElementById("MyElement").classList.contains('MyClass') )
Similarly, you can do the same thing using jQuery also, using hasClass
if ( $('#MyElement').hasClass('MyClass') )
Toggle Class Name
In this article, we have learnt how to change element’s class name. We have also seen several different ways to change an element’s class name. Be clear about whether you want to add/remove or replace the class name of an element, since replacing the class name will wipe off all old class name values.
How to Disable/Enable Input Using jQuery
How to Run 32-bit App on 64-bit Linux
How to Change File Extension of Multiple Files in Python