How can I Change an HTML Element’s Class With JavaScript or JQuery?

Change Element's Class

In this practical HTML guide, we will show you how to change an HTML element’s class using Vanilla JavaScript or JQuery with examples.

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.

Using className

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:

Read Also  The GNU C Library version 2.24 now available

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.

There you have it. That is the way to change an element’s class in HTML using either vanilla JavaScript of the JQuery library.

Ref: [1], [2]