đŸ•·ïž Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 131 (from laksa196)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

â„č Skipped - page is already crawled

📄
INDEXABLE
✅
CRAWLED
6 days ago
đŸ€–
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.2 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://favtutor.com/articles/add-class-to-element-javascript/
Last Crawled2026-03-31 09:45:17 (6 days ago)
First Indexed2024-01-29 06:57:31 (2 years ago)
HTTP Status Code200
Meta TitleAdding a Class to an Element in JavaScript (with code)
Meta DescriptionLearn how to add a class to an element in JavaScript using className, classList, toggle and setAttribute method, with examples.
Meta Canonicalnull
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
[![Articles by FavTutor](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)![Articles by FavTutor](https://favtutor.com/articles/wp-content/uploads/2023/11/Articles_by-removebg-preview.png)](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 [![FavTutor](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)![FavTutor](https://favtutor.com/articles/wp-content/uploads/2023/11/Articles_by-removebg-preview.png)](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 [![Articles by FavTutor](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)![Articles by FavTutor](https://favtutor.com/articles/wp-content/uploads/2023/11/Articles_by-removebg-preview.png)](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) ![Nikita Arora](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2080%2080'%3E%3C/svg%3E) ![Nikita Arora](https://favtutor.com/articles/wp-content/uploads/2024/01/Nikita-Arora-FavTutor-150x150.png) 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 [![Methods to Add Class to an Element](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20750%20422'%3E%3C/svg%3E) ![Methods to Add Class to an Element](https://favtutor.com/articles/wp-content/uploads/2024/01/Methods-to-Add-Class-to-an-Element-750x422.png)](https://favtutor.com/articles/wp-content/uploads/2024/01/Methods-to-Add-Class-to-an-Element.png) [![Follow us on Google News](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20200%200'%3E%3C/svg%3E)![Follow us on Google News](https://favtutor.com/articles/wp-content/uploads/2025/02/Follow-Google-News.png)](https://news.google.com/publications/CAAqBwgKMMmBpwww24m1BA?ceid=IN:en&oc=3) [![Subscribe to our newsletter](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20350%200'%3E%3C/svg%3E)![Subscribe to our newsletter](https://favtutor.com/articles/wp-content/uploads/2025/02/FavTutor-Newsletter-Banner.jpg)](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](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2080%2080'%3E%3C/svg%3E) ![Nikita Arora](https://favtutor.com/articles/wp-content/uploads/2024/01/Nikita-Arora-FavTutor-150x150.png) ### [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** [![Javascript Animation Libraries](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==)](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/) [![JavaScript Interview Questions](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==)](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/) [![Best React UI Component Libraries](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==)](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/) [![Currying in JavaScript](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==)](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/) [![Javascript Format Currency](data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==)](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
[![Follow us on Google News](https://favtutor.com/articles/wp-content/uploads/2025/02/Follow-Google-News.png)](https://news.google.com/publications/CAAqBwgKMMmBpwww24m1BA?ceid=IN:en&oc=3) [![Subscribe to our newsletter](https://favtutor.com/articles/wp-content/uploads/2025/02/FavTutor-Newsletter-Banner.jpg)](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.
Shard131 (laksa)
Root Hash1162696084485777131
Unparsed URLcom,favtutor!/articles/add-class-to-element-javascript/ s443