Adding a class to an element is quite easy in JavaScript. There are 3 different approaches that are commonly used to add a class to an element dynamically using JavaScript.
These three approaches are:
Let’s discuss each approach in detail with a live working example.
Using the classList.add() Method
The add()
method is used to add one or more classes to an element at a time. If the class name to be added already exists, the targeted element is not affected.
Here is its syntax:
element.classList.add('class_name');
See the following example, where we are adding a class .yellow
to the div element on the button click:
Example:
let div = document.getElementById('myDiv'); function addClass(){ div.classList.add('yellow'); }
If you want to add multiple classes to an element using the classList.add()
method, you have to separate them with commas(,)
.
element.classList.add('class1', 'class2', 'class3');
See the following example:
Example:
let div = document.getElementById('myDiv'); function addClass(){ // Add multiple classes div.classList.add('yellow', 'red'); }
Using the className Property
The className
property can also be used to add single or multiple classes to an element.
Here is the syntax:
element.className = 'class_name';
But, keep in mind that the className
property will remove all existing classes from the element and will replace them with the new ones.
Example:
let div = document.getElementById('myDiv'); function addClass(){ div.className = 'yellow'; }
If you want to add multiple classes, you have to separate them with white spaces.
element.className = 'class1 class2 class3 ...';
See the following example where we are adding .yellow
and .red
classes to the div element on the button click:
Example:
let div = document.getElementById('myDiv'); function addClass(){ div.className = 'yellow red'; }
Using the setAttribute() Method
The third and last approach is to use the setAttribute()
method. This is also very similar to the className
approach that we discussed above.
It also removes the existing classes from the element and replaces them with new ones.
Here is the syntax:
element.setAttribute('attr_name','class_name');
See the following working example:
Example:
let div = document.getElementById('myDiv'); function addClass(){ // Add class .yellow to the div div.setAttribute('class','yellow'); }
To add multiple classes using the setAttribute()
method, separate them with spaces:
element.setAttribute('class','class1 class2 class3');
Conclusion
In this article, we have learned three different ways to add single or multiple classes to an element dynamically with JavaScript.
However, we recommend you to always use the classList.add()
method. Because it doesn’t remove existing classes from the element.
Whereas, the latter two methods remove all existing classes from the element while adding the new.
Thanks for reading.