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

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:

[js]
// 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’) )
[/js]

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.

[js]
// replaces all existing classes with MyClass
document.getElementById(“ElementID”).className = “MyClass”;
[/js]

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

[js]
// Note the plus: (+=)
document.getElementById(“ElementID”).className += ” MyClass”;
[/js]

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:

[js]
document.getElementById(“ElementID”).className =
document.getElementById(“ElementID”).className.replace
( /(?:^|\s)MyClass(?!\S)/g , ” );
[/js]

Check if a Particular Class Exists:

[js]
if ( document.getElementById(“#ElementID”).className.match(/(?:^|\s)MyClass(?!\S)/) )
[/js]

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.

See also  How to Create Apache Virtual Host for Your Website

[js]
// 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’) )
[/js]

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]

Available under:
Articles, Guides, Technology