Add Remove, Toggle or Replace Class of an Element in JavaScript
Almost all website projects that we work on require us to change the classes of different HTML elements at one time or other. We can do this very easily using jQuery. However, using a library just to change or manipulate the classes of different DOM element is overkill. In this post, we will cover different methods to achieve all this using pure JavaScript.
Add a Class to an HTML Element Using className
The className
property can be used to get or set the value of the class
attribute of any DOM element. The returned string contains all the classes of current element separated by a space. We can simply use the +=
operator to append any new classes to our element.
JavaScript
document.getElementById("theId").className += " extraClass";
document.querySelector("selector").className += " extraClass";
If you want to add a class to multiple HTML elements at once, you can use the document.querySelectorAll()
method to do so.
JavaScript
var elems = document.querySelectorAll("selector");
var elemCount = elems.length;
for (var i = 0; i < elemCount; i++) {
elems[i].className += " extraClass";
}
You can also use the document.querySelectorAll()
method to assign extra classes a selected HTML element at a specific index.
JavaScript
document.querySelectorAll("selector")[index] += " extraClass";
One disadvantage of adding classes this way is that if you are not careful, a class might be added several times. We can implement a check to see if class already exists for an HTML element and not add it if it does.
JavaScript
var elem = document.getElementById("theId");
if(elem.className.match( /(^|\s+)extraClass($|\s+)/g)) {
elem.className += " extraClass";
}
Remove a Class From an HTML Element Using className
You can also use the className
property to remove a specific class from the class
attribute of an HTML element. This requires the use of regex to replace the unwanted class with an empty string.
JavaScript
var elem = document.getElementById("theId");
elem.className = elem.className.replace( /(^|\s+)extraClass($|\s+)/g , '' );
In the above regular expression, the first capture group either captures the beginning of a string or any whitespace characters. Similarly, the second capture group either captures the end of a string or any whitespace characters. The string between these two capture groups is the class name that you want to replace. Here are some of the results of using the above regular expression to replace unwanted classes:
JavaScript
Regular Expression — (^|\s+)dark($|\s+)/g
Classes — "heading page-title dark large"
After Removal — "heading page-title large"
Regular Expression — (^|\s+)title($|\s+)/g
Classes — "heading page-title dark large"
After Removal — "heading page-title dark large"
Regular Expression — (^|\s+)large($|\s+)/g
Classes — "heading page-title dark large"
After Removal — "heading page-title dark"
In the second case, there was no title
class in the whole list so nothing was replaced. The page-title
class remained intact.
Just like the previous section, you can loop through multiple elements and remove a class from all of them using the docment.querySelectorAll()
method.
Replace all Classes of an HTML Element with New Ones Using className
You can also replace all classes of an HTML element with new ones by assigning the new class string to that element instead of appending it to the original set of classes.
JavaScript
document.getElementById("theId").className = "firstClass secondClass";
document.querySelector("selector").className = "firstClass";
Similarly, you can assign new classes to multiple elements by looping over them.
JavaScript
var elems = document.querySelectorAll("selector");
var elemCount = elems.length;
for (var i = 0; i < elemCount; i++) {
elems[i].className = "extraClass";
}
Adding, Removing and Replacing Classes Using classList
If you are working with modern browsers, you can avoid the use of regular expressions while changing the classes of an HTML element. All modern browsers as well as Internet Explorer 10 and above support a classList
property for DOM elements. This property has some useful methods which can add and remove classes from the class
attribute of any HTML element.
The add(String [, String])
method accepts name of one or more classes as its parameters. These classes are added to the original HTML element on which this method was called. If any of those classes already exist in that element, there will be ignored. This way you can be sure that the same class is not added multiple times.
The remove(String [, String])
method also accepts name of one or more classes as its parameters. All the classes supplied to this method will be deleted from the list of classes initially applied on the calling HTML element. One good thing about the method is that it will not through an error if the class that you’re going to delete does not already exist in that element.
You can also use the toggle(String [, force])
method to toggle a class currently applied on the calling HTML element. If the class already exists, it will be removed and the method will return false
. If a class does not exist, it will be added to the list of classes and the method will return true
. The force
parameter is a Boolean value which can be used to forcefully add or remove a class from the calling HTML element. A class will be added if the value of force
evaluates to true
. Similarly, the class will be removed if the value of force
evaluates to false
.
Instead of adding or removing classes, you might sometimes be interested in replacing an old class with a new one. This can be achieved using the replace(oldClass, newClass)
method. The first parameter passed to this method is the old class that you want to replace. The second parameter is the new class meant to take the place of old class.
The class list property also has a contains(String)
method which can check if an HTML element contains a class or not.
JavaScript
var theClassList = document.querySelector("selector").classList;
theClassList.add('firstClass');
theClassList.remove('secondClass');
theClassList.toggle('thirdClass');
theClassList.replace('thirdClass', 'fourthClass');
Quick Summary
Let’s recap everything that we have covered in this tutorial.
- If you have to support older browsers the best way to add, remove or replace any class in an HTML element is to use the
className
property. However, you will have to be careful about a few things like not adding a class multiple times etc. - If you don’t have to support older browsers the best way to change the classes of an HTML element is to use the
classList
property. This will take care of everything for you.
Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other techniques to add, remove or replace the classes of an HTML element using JavaScript.
Rate this post —
sorry the code doesn’t work
Hi aria,
Could you please tell me which part of the code isn’t working?