âčïž Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.2 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://favtutor.com/articles/add-class-to-element-javascript/ |
| Last Crawled | 2026-03-31 09:45:17 (6 days ago) |
| First Indexed | 2024-01-29 06:57:31 (2 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Adding a Class to an Element in JavaScript (with code) |
| Meta Description | Learn how to add a class to an element in JavaScript using className, classList, toggle and setAttribute method, with examples. |
| Meta Canonical | null |
| Boilerpipe Text | Â
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. |
| Markdown | [](https://favtutor.com/articles/)
- [AI News](https://favtutor.com/articles/category/ai/)
- [Data Structures](https://favtutor.com/articles/category/data-structures-algorithms/)
- [Web Developement](https://favtutor.com/articles/category/web-development/)
- [AI Code GeneratorNEW](https://favtutor.com/ai-code-generator)
- [Student Help](https://students.favtutor.com/memberSignup)
- [Main Website](https://favtutor.com/)
No Result
View All Result
[](https://favtutor.com/articles/)
- [AI News](https://favtutor.com/articles/category/ai/)
- [Data Structures](https://favtutor.com/articles/category/data-structures-algorithms/)
- [Web Developement](https://favtutor.com/articles/category/web-development/)
- [AI Code GeneratorNEW](https://favtutor.com/ai-code-generator)
- [Student Help](https://students.favtutor.com/memberSignup)
- [Main Website](https://favtutor.com/)
No Result
View All Result
[](https://favtutor.com/articles/)
No Result
View All Result
[Home](https://favtutor.com/articles) [Web Developement](https://favtutor.com/articles/category/web-development/)
# Adding a Class to an Element in JavaScript (with code)


by [Nikita Arora](https://favtutor.com/articles/author/nikita-arora/)
[January 29, 2024](https://favtutor.com/articles/add-class-to-element-javascript/)
Reading Time: 6 mins read
[ ](https://favtutor.com/articles/wp-content/uploads/2024/01/Methods-to-Add-Class-to-an-Element.png)
[](https://news.google.com/publications/CAAqBwgKMMmBpwww24m1BA?ceid=IN:en&oc=3)
[](https://bit.ly/favtutor-newsletter)
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](https://favtutor.com/articles/link-javascript-html/).
## **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.
[Share](https://www.linkedin.com/shareArticle?url=https%3A%2F%2Ffavtutor.com%2Farticles%2Fadd-class-to-element-javascript%2F&title=Adding%20a%20Class%20to%20an%20Element%20in%20JavaScript%20%28with%20code%29)[Tweet](https://twitter.com/intent/tweet?text=Adding%20a%20Class%20to%20an%20Element%20in%20JavaScript%20%28with%20code%29%20via%20%40favtutor&url=https%3A%2F%2Ffavtutor.com%2Farticles%2Fadd-class-to-element-javascript%2F)[Share](https://reddit.com/submit?url=https%3A%2F%2Ffavtutor.com%2Farticles%2Fadd-class-to-element-javascript%2F&title=Adding%20a%20Class%20to%20an%20Element%20in%20JavaScript%20%28with%20code%29)[Send](https://api.whatsapp.com/send?text=Adding%20a%20Class%20to%20an%20Element%20in%20JavaScript%20%28with%20code%29%0Ahttps%3A%2F%2Ffavtutor.com%2Farticles%2Fadd-class-to-element-javascript%2F)[Send](https://favtutor.com/cdn-cgi/l/email-protection#d8e7abadbab2bdbbace599bcbcb1b6bffdeae8b9fdeae89bb4b9ababfdeae8acb7fdeae8b9b6fdeae89db4bdb5bdb6acfdeae8b1b6fdeae892b9aeb98bbbaab1a8acfdeae8fdeae0afb1acb0fdeae8bbb7bcbdfdeae1feb9b5a8e3bab7bca1e5b0acaca8abfdeb99fdea9efdea9ebeb9aeacadacb7aaf6bbb7b5fdea9eb9aaacb1bbb4bdabfdea9eb9bcbcf5bbb4b9ababf5acb7f5bdb4bdb5bdb6acf5b2b9aeb9abbbaab1a8acfdea9e)


### [Nikita Arora](https://favtutor.com/articles/author/nikita-arora/)
I'm Nikita, a B.Tech Computer Engineering student. My passion lies in web development, data structures, and algorithms. Committed to continuous learning, I find immense joy in sharing insights and fostering collaboration among like-minded peers in web development. Excited about exploring interesting opportunities in technology.
### Related**Posts**
[](https://favtutor.com/articles/javascript-animation-libraries/)
### [Top 10 JavaScript Animation Libraries in 2025](https://favtutor.com/articles/javascript-animation-libraries/)
[February 19, 2025](https://favtutor.com/articles/javascript-animation-libraries/)
[](https://favtutor.com/articles/javascript-interview-questions/)
### [Top 40 JavaScript Interview Questions and Answers in 2024](https://favtutor.com/articles/javascript-interview-questions/)
[April 1, 2025](https://favtutor.com/articles/javascript-interview-questions/)
[](https://favtutor.com/articles/best-react-component-libraries/)
### [10 Must-Know React UI Component Libraries for Web Devs 2024](https://favtutor.com/articles/best-react-component-libraries/)
[May 7, 2024](https://favtutor.com/articles/best-react-component-libraries/)
[](https://favtutor.com/articles/currying-javascript/)
### [Currying in JavaScript Explained (with Examples)](https://favtutor.com/articles/currying-javascript/)
[March 15, 2024](https://favtutor.com/articles/currying-javascript/)
[](https://favtutor.com/articles/javascript-format-currency/)
### [Javascript Program for Format Currency](https://favtutor.com/articles/javascript-format-currency/)
[April 8, 2025](https://favtutor.com/articles/javascript-format-currency/)
### About FavTutor
FavTutor is a trusted online tutoring service to connects students with expert tutors to provide guidance on Computer Science subjects like Java, Python, C, C++, SQL, Data Science, Statistics, etc.
### Categories
- [AI News, Research & Latest Updates](https://favtutor.com/articles/category/ai/)
- [Trending](https://favtutor.com/articles/category/trending/)
- [Data Structures](https://favtutor.com/articles/category/data-structures-algorithms/)
- [Web Developement](https://favtutor.com/articles/category/web-development/)
- [Data Science](https://favtutor.com/articles/category/data-science/)
### Important Subjects
- [Python Assignment Help](https://favtutor.com/python-assignment-help)
- [C++ Help](https://favtutor.com/cpp-homework-help)
- [R Programming Help](https://favtutor.com/r-homework-help)
- [Java Homework Help](https://favtutor.com/java-homework-help)
- [Programming Help](https://favtutor.com/programming-help)
### Resources
- [About Us](https://favtutor.com/about)
- [Contact Us](https://favtutor.com/contact)
- [Editorial Policy](https://favtutor.com/editorial-policy)
- [Privacy Policy](https://favtutor.com/privacy)
- [Terms and Conditions](https://favtutor.com/terms)
Website listed on [Ecomswap](https://ecomswap.io/). © Copyright 2025 All Rights Reserved.
No Result
View All Result
- [AI News](https://favtutor.com/articles/category/ai/)
- [Data Structures](https://favtutor.com/articles/category/data-structures-algorithms/)
- [Web Developement](https://favtutor.com/articles/category/web-development/)
- [AI Code Generator](https://favtutor.com/ai-code-generator)
- [Student Help](https://students.favtutor.com/memberSignup)
- [Main Website](https://favtutor.com/)
Website listed on [Ecomswap](https://ecomswap.io/). © Copyright 2025 All Rights Reserved. |
| Readable Markdown | [](https://news.google.com/publications/CAAqBwgKMMmBpwww24m1BA?ceid=IN:en&oc=3) [](https://bit.ly/favtutor-newsletter)
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](https://favtutor.com/articles/link-javascript-html/).
## **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. |
| Shard | 131 (laksa) |
| Root Hash | 1162696084485777131 |
| Unparsed URL | com,favtutor!/articles/add-class-to-element-javascript/ s443 |