Web browsers allow users to add or remove classes attached to an element in response to mouse clicks, taps, or any other event.
The ability to change an HTML Element’s class is a very important function in making web pages more interactive and dynamic. You can use it to change the element’s appearance or even behavior.
Let’s See How to Change an Element’s Class
Modern browsers have a read-only property called classList that returns a live DOMTokenList collection of the class attributes of the element.
classList provides methods to conveniently add or remove classes as seen below:
The above will not work in versions less than Internet Explorer 10.
You can also use className to replace all existing classes with one or more new classes.
To preserve the existing classes while adding a new class to an element, use this:
Remove a Single Class From an Element Using className:
You can remove a single class from an element without affecting other classes if they exist using a regex replace seen below:
Check if a Particular Class Exists:
Change Element’s Class with jQuery
You can also use JQuery‘s simpler syntax to change the classes in an HTML element in case you intend to use the library in your project.