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
document.getElementById("ElementID").classList.add('MyClass');

// remove a class
document.getElementById("ElementID").classList.remove('MyClass');

// toggle a class
document.getElementById("ElementID").classList.toggle('MyClass');

// 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 =
   document.getElementById("ElementID").className.replace
      ( /(?:^|\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
$('#ElementID').addClass('MyClass');

// remove the class
$('#ElementID').removeClass('MyClass');

// toggle the class in or out
$('#ElementID').toggleClass('MyClass');

// 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