Adding a class to an element is a common task when it comes to manipulating HTML elements dynamically. In this article, we will learn how to add a class to an element in JavaScript using various methods.
4 Methods to Add a Class to an Element Using JavaScript
As we know, JavaScript is the programming language used to dynamically change the behavior on a webpage by manipulating the element. If we can add a class to an element using JavaScript, we can apply new styles to elements based on user interactions or responsive design. This way makes the HTML markup cleaner and the JS code will be maintainable.
Let’s check out the four different methods to add a class to an element using JavaScript along with examples:
1) Using .className Property
The className property is the recommended way to add a class to an element in JavaScript. This property represents the class attribute of an element and allows us to assign or append class names.
For example:
// Get the element by its ID var myElement = document.getElementById('myElement'); // Add a class to the element using className myElement.className += ' newClass';
Here myElement refers to the HTML element to which we want to add the class, and “newClass” is the name of the class we want to add.
If we want to add multiple classes together we can simply add them using spaces:
// Get the element by its ID var myElement = document.getElementById('myElement'); // Add a class to the element using className myElement.className += ' newClass1 newClass2 newClass3';
Here by using +=, we are appending to existing classes. If we want to replace current classes, i.e. we want to assign new classes and remove previous classes then we can simply use = instead of +=. Here’s the code:
// Get the element by its ID var myElement = document.getElementById('myElement'); // Add a class to the element using className myElement.className = ' newClass';
While using +=, we are appending a class to existing classes by concatenating classes. If we do not add a space before ‘newClass’, then we will join two class names and this will lead to unintended results:
<body> <!-- An example element with an ID and an existing class --> <div id="myElement" class="existingClass">This is a sample element.</div> <script> // Get the element by its ID var myElement = document.getElementById('myElement'); // Add a class without a space using className myElement.className += 'newClass'; </script> </body>
Here, the original class of the element is ‘existingClass’, and we attempt to add a new class named ‘newClass’ without a space before it. The result will be that the classes are concatenated without a space, leading to a single combined name(‘existingClassnewClass’).
2) Using classList.add() Method
The classList property of an HTML element provides a set of methods to manage classes. The .add() method specifically allows us to add one or more classes to an element. Using classList.add() method, we can add a class to an element in JavaScript.
This method is preferred over manipulating ‘className’ directly because it is more explicit and doesn’t replace existing classes.
// Get the element by its ID var myElement = document.getElementById('myElement'); // Add a class to the element using classList.add() myElement.classList.add('newClass');
Here myElement refers to the HTML element to which we want to add the class, and “newClass” is the name of the class we want to add.
If we want to add multiple classes together, we have to pass each class name as a separate argument to the ‘add()’ method. Here’s an example:
// Get the element by its ID var myElement = document.getElementById('myElement'); // Add multiple classes to the element using classList.add() myElement.classList.add('class1', 'class2', 'class3');
In this example, the ‘classList.add()’ method is used to add three classes(‘class1’, ‘class2’, and ‘class3’) to the element with the ID ‘myElement’.
3) Using setAttribute() Method
Similar to the ‘className’ property, this method also replaces the entire class attribute, therefore causing unintended results.
The setAttribute() method in JavaScript allows us to set values to attributes of an element. If the attribute already exists, the method updates its value. Otherwise, a new attribute is added to the element along with the assigned value.
To add a class to an element using the setAttribute() method, we need to specify the attribute name as ‘class’ and the value as the name of the class we want to add. For example:
// Get the element by its ID var Ele = document.getElementById('myElement'); // Add a class to the element using className Ele.className = 'previousClass'; // Get the element by its ID var myElement = document.getElementById('myElement'); // Add a class to the element using setAttribute() myElement.setAttribute('class', 'newClass');
Here, by using the setAttribute() method, the ‘previousClass’ of the element is replaced by ‘newClass’.
4) Using classList.toggle() Method
The classList.toggle() method is a very unique apporach to add a class name to an element. When you use this method, it adds the specified class if it’s not present and removes it if it’s present.
For example:
// Get the element by its ID var myElement = document.getElementById('myElement'); // Toggle a class on the element using classList.toggle() myElement.classList.toggle('active');
In this example, if the element initially has the class ‘active’, the toggle() method will remove it. If the element doesn’t have the class ‘active’, the method will add it.
This method is used when we want to add or remove a class based on certain conditions (in response to events or state changes) without explicitly checking for its presence. Note that it does not remove other classes.
Also, to make your code much better, you need to know different ways to link HTML to JavaScript.
Conclusion
We have covered four different approaches for adding a class name to an element using JavaScript. Each method offers its unique advantages and understanding this gives us the flexibility to choose the one that fits our needs.