If we’re working with web front end apps, then changing an element’s class is something that we’ve to do often.
In this article, we’ll take a look at how to change an element’s class with JavaScript.
The classList Property
An element has the classList
property to let us manipulate the classes that are applied to the element.
For instance, if we have a div:
<div>
hello world
</div>
Then to add a class to the div, we can write:
document.querySelector("div").classList.add('hello');
We call add
to add the 'hello'
class to the div.
If the hello
class is already added, then nothing will be done.
To remove a class, we can call the classList.remove
method:
document.querySelector("div").classList.remove('hello');
To check if a class is already present in an element, we can use the classList.contains
method:
document.querySelector("div").classList.contains('hello');
It returns true
if the class is applied to the div and false
otherwise.
And to toggle class that’s applied to an element, we can call the classList.toggle
method:
document.querySelector("div").classList.toggle('hello');
If the hello
class is applied to the div, then it’ll be removed.
Otherwise, the hello
class will be added to the div.
This is available in most recent browsers.
The className Property
Another way to manipulate classes of an element is to manipulate the className
string property.
For instance, we can write:
document.querySelector("div").className = 'hello';
We get the div and set the className
to 'hello'
to set the class
attribute of the div to 'hello'
.
To add a class by manipulating the className
property, we can write:
document.querySelector("div").className += ' hello';
We add a space and hello
to add the hello
class to the div.
To remove the hello
class, we can use the replace
method:
document.querySelector("div").className.replace(/(?:^|s)hello(?!S)/g, '')
We check for hello
with possible spaces at the start or end of the class name and replace them with an empty string.
The g
flag will find all the instances of this and do the replacement on all of them.
To find if a class is in the div, we can write:
document.querySelector("div").className.match(/(?:^|s)hello(?!S)/)
We call match
with the regex that matches hello
with whitespace before or after it to check if the class is in the className
string.
Conclusion
The best and easiest way to manipulate classes of an HTML element is to use the classList
property.
Alternatively, we can also manipulate the className
string property to change the class
attribute of an element.