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

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

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:

// add a class

// remove a class

// toggle a class

// check if class is present
if ( document.getElementById("ElementID").classList.contains('MyClass') );

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.

// replaces all existing classes with MyClass
document.getElementById("ElementID").className = "MyClass";

To preserve the existing classes while adding a new class to an element, use this:

// Note the plus: (+=)
document.getElementById("ElementID").className += " MyClass";

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:

document.getElementById("ElementID").className =
      ( /(?:^|\s)MyClass(?!\S)/g , '' );

Check if a Particular Class Exists:

if ( document.getElementById("#ElementID").className.match(/(?:^|\s)MyClass(?!\S)/) )

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.

// add the class

// remove the class

// toggle the class in or out

// check if the class exists
if ( $('#ElementID').hasClass('MyClass') )

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]

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

Available under:
Articles, Guides, Technology