🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 54 (from laksa129)

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
2 months ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH2.4 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://codedamn.com/news/javascript/how-to-add-class-to-element
Last Crawled2026-01-30 14:03:45 (2 months ago)
First Indexed2022-09-20 17:59:57 (3 years ago)
HTTP Status Code200
Meta TitleHow To Add Class To Element In JavaScript – Complete Guide
Meta Description<p>Javascript is one of the key elements behind adding interactivity to a website. Without it, thinking of creating a fully interactive and functional website is next to impossible. Among the many amazing features of this language is the variety of functions and methods it offers to make a developer...
Meta Canonicalnull
Boilerpipe Text
Javascript is one of the key elements behind adding interactivity to a website. Without it, thinking of creating a fully interactive and functional website is next to impossible. Among the many amazing features of this language is the variety of functions and methods it offers to make a developer’s life easier and more convenient. Using javascript, we can modify DOM elements or perform calculations behind the scenes while static HTML is displayed. The goal of this tutorial is to demonstrate in-depth how Javascript can be used to add classes to HTML elements and perform a number of other useful operations with its help. With that being said, let’s begin! Introduction CSS uses the class attribute to perform a series of actions on elements with the same class name. DOM (Document Object Model) is a method of manipulating HTML documents. Javascript allows you to add classes to the body of your webpage through document.body or document.getElementById("id") . Classes can either be added directly to an HTML element as an attribute (Ex: <p class="para-class"> ) or by using JavaScript (which is what we’ll look at in this section). There are three different ways to add classes to an element using javascript. Let’s explore each of those approaches one by one. Using .className property The  .className   property can be used to set the name of the class of an element. Using this property, we can add a single class or multiple classes to an HTML element without replacing its existing classes. In addition, this property can also be used to return an element’s class attribute value. Syntax to set the class name: HTMLelement.className = "new_class"; Code language: HTML, XML ( xml ) In this case, “ new_class ” specifies the element’s class name. We can add multiple classes by separating their names with spaces, for instance, “ new_class1 new_class2 “. To return the class name/names: HTMLelement.className; Code language: HTML, XML ( xml ) The property returns a string type representing a class or lists of classes of elements separated by space. Example Below is an example, that uses the  .className  property to add the class “ new-para-class “  to the paragraph element having id  “ para “ . The CSS is applied to the corresponding paragraph using the class name  “ new-para-class “ . In order to see the effect, we need to click the given HTML button  “ Add New Class “  to see the effect. Note : If you assign a class name directly to the  className property, the existing classes will be overwritten. HTML Code: <!doctype HTML > < html > < head > < title > codedamn HTML Playground </ title > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < link rel = "stylesheet" href = "/style.css" /> </ head > < body > < h1 > Welcome to codedamn </ h1 > < p id = "para" class = "old-para-class" > This para's class will get replaced with the new one. </ p > < button onclick = "addClass()" > Add New Class </ button > < script src = "https://bit.ly/codedamn-web-console" > </ script > < script src = "/script.js" > </ script > </ body > </ html > Code language: HTML, XML ( xml ) CSS Code: body { padding : 10px ; margin : 0 ; font-family : -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; line-height : 1.6 ; font-size : 18px ; } .old-para-class { background : #96bfff ; } .new-para-class { background : #ff96ab ; } Code language: CSS ( css ) Javascript Code: const para = document .getElementById( "para" ); function addClass ( ) { para.className= "new-para-class" ; } Code language: JavaScript ( javascript ) Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. Adding multiple classes You can add new classes without replacing older ones by using the += operator. This works by keeping older classes and adding new ones. Note: When adding a class, make sure to add a space " " before the class name. Let’s modify the existing example to see how it works. HTML Code: ... ... <p id= "para" class = "old-para-class" >This para 's class will get replaced with the new one.</p> ... ... Code language: JavaScript ( javascript ) CSS code: ... ... .old-para- class { color : # 2e4 bab; } .new-para- class { background : #ff96ab; } ... ... Code language: JavaScript ( javascript ) Javascript code: ... ... function addClass(){ para.className += " new-para-class" ; //using the += operator } Code language: JavaScript ( javascript ) Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. Getting the class name Using the .className property, we can also retrieve the class names of the paragraph elements having id = "para" . HTML Code: ... ... <p id= "para" class = "old-para-class" >Clicking the below button will add a new class without removing the existing one .</ p > < p > Para Class :</ p > < p id = "show-class" class = "show-class-para" >< /p> <!-- This element will show the classes applied on first para. --> <button onclick="addClass()">Add New Class</ button> ... ... Code language: JavaScript ( javascript ) Javascript Code: const para = document .getElementById( "para" ); const showClassPara = document .getElementById( "show-class" ); function addClass ( ) { para.className += " new-para-class" ; showClassPara.innerHTML += para.className; //using the className property to get the element and adding to p element with id show-class } Code language: JavaScript ( javascript ) Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. Using .classList.add() method In HTML, the .classList property returns the DOMTokenList representation of the element’s class attribute. This .classList property has a .add() method that can be used to add a class name to an HTML element. Here is an example of how you would use .add method in Javascript: HTMLelement .classList .add (" new_class "); Code language: CSS ( css ) Examples We will use the same files as before and only change the CSS and Javascript. CSS Code: ... ... .new-para-class1 { background : #ff96ab ; } Code language: CSS ( css ) Javascript Code: ... ... function addClass () { para.classList.add( "new-para-class1" ); ... ... Code language: PHP ( php ) Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. Adding multiple classes The add() method is also capable of adding multiple classes simultaneously. When adding multiple classes, separate the classes with a comma. CSS Code: ... ... .new-para-class1 { background : #ff96ab ; } .new-para-class2 { font-style : italic; } ... ... Code language: CSS ( css ) Javascript Code: ... ... function addClass () { para.classList.add( "new-para-class1" , "new-para-class2" ); //seperating multiple classes with the help of comma ... ... Code language: PHP ( php ) Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. Using .setAttribute() Method An element can be modified by adding an attribute using the setAttribute method in Javascript. Since classes are also element attributes, we can add them setAttribute method to add a class. There are two parameters required by this method, the attribute’s name, and its value . Here is an example of how we would use this method in Javascript: HTMLelmeent.setAttribute('class', 'new_class'); Code language: HTML, XML ( xml ) Examples Let’s take the previous example and change some lines to see how it works: Javascript Code: ... ... function addClass () { para.setAttribute( 'class' , 'new-para-class1' ) //using the setAttribute class to set the class name for the previous para element. ... Code language: PHP ( php ) Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. Adding multiple classes In order to add multiple classes to the same element, we can pass a list of multiple class names separated by spaces to the setAttribute method. Javascript Code: ... ... function addClass () { para.setAttribute( 'class' , 'new-para-class1 new-para-class2' ) ... Code language: PHP ( php ) Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. Some Other Useful methods Deleting a class The .classList property also has a remove() method which allows you to delete a class from an HTML element. Syntax example: HTMLelement.classList.remove("class_name") Code language: HTML, XML ( xml ) Toggling a class Similarly, The toggle() method of classList property can be used to toggle a class in javascript. Syntax example: HTMLelement.classList.toggle("class_name") Code language: HTML, XML ( xml ) Conclusion We just discussed how to add classes to elements. These properties allow you to add single or multiple classes to an element. You can also add a class when the element is hovered by using the onmouseover event. I hope this article explained everything you need to know about adding class names to HTML elements. If you ever feel lost and want help understanding where to start your coding journey, there are amazing courses and blogs for web development and other coding concepts on Codedamn . Remember to practice coding on a daily basis. You can play around with your code on Codedamn’s online compiler as well. Finally, If you are interested in my content and would like to connect, then you can find me on Linkedin or Twitter . Thank You for reading!
Markdown
![facebook pixel](https://www.facebook.com/tr?id=3250905641816288&ev=PageView&noscript=1) [codedamn](https://codedamn.com/) Categories [codedamn](https://codedamn.com/) Categories Saturday, Sep 17th 2022 # How To Add Class To Element In JavaScript – Complete Guide Posted by Table of contents - [Introduction](https://codedamn.com/news/javascript/how-to-add-class-to-element#introduction) - [Using .className property](https://codedamn.com/news/javascript/how-to-add-class-to-element#using_classname_property) - [Using .classList.add() method](https://codedamn.com/news/javascript/how-to-add-class-to-element#using_classlistadd_method) - [Using .setAttribute() Method](https://codedamn.com/news/javascript/how-to-add-class-to-element#using_setattribute_method) - [Some Other Useful methods](https://codedamn.com/news/javascript/how-to-add-class-to-element#some_other_useful_methods) - [Conclusion](https://codedamn.com/news/javascript/how-to-add-class-to-element#conclusion) ![How To Add Class To Element In JavaScript – Complete Guide](https://wsrv.nl/?url=https%3A%2F%2Fcodedamn-blog.s3.amazonaws.com%2Fwp-content%2Fuploads%2F2022%2F09%2F15132631%2Fadd_classes_js.jpg&w=1280&q=82&output=webp) Javascript is one of the key elements behind adding interactivity to a website. Without it, thinking of creating a fully interactive and functional website is next to impossible. Among the many amazing features of this language is the variety of functions and methods it offers to make a developer’s life easier and more convenient. Using javascript, we can modify DOM elements or perform calculations behind the scenes while static HTML is displayed. The goal of this tutorial is to demonstrate in-depth how Javascript can be used to add classes to HTML elements and perform a number of other useful operations with its help. With that being said, let’s begin\! ## Introduction CSS uses the **class** attribute to perform a series of actions on elements with the same class name. **DOM** (Document Object Model) is a method of manipulating HTML documents. Javascript allows you to add classes to the body of your webpage through `document.body` or `document.getElementById("id")`. Classes can either be added directly to an HTML element as an attribute (Ex: `<p class="para-class">`) or by using JavaScript (which is what we’ll look at in this section). There are three different ways to add classes to an element using javascript. Let’s explore each of those approaches one by one. ## Using .className property The `.className`property can be used to set the name of the class of an element. Using this property, we can add a single class or multiple classes to an HTML element without replacing its existing classes. In addition, this property can also be used to return an element’s class attribute value. Syntax to set the class name: ``` HTMLelement.className = "new_class";Code language: HTML, XML (xml) ``` In this case, “`new_class`” specifies the element’s class name. We can add multiple classes by separating their names with spaces, for instance, “`new_class1 new_class2`“. To return the class name/names: ``` HTMLelement.className;Code language: HTML, XML (xml) ``` The property returns a string type representing a class or lists of classes of elements separated by space. ### Example Below is an example, that uses the `.className` property to add the class ***“***`new-para-class`***“*** to the paragraph element having id ***“***`para`***“***. The CSS is applied to the corresponding paragraph using the class name ***“***`new-para-class`***“***. In order to see the effect, we need to click the given HTML button **“**`Add New Class`**“** to see the effect. **Note**: If you assign a class name directly to the `className` property, the existing classes will be overwritten. #### HTML Code: ``` Code language: HTML, XML (xml) ``` #### CSS Code: ``` Code language: CSS (css) ``` #### Javascript Code: ``` Code language: JavaScript (javascript) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151007/1-2.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151010/2.jpeg) ### Adding multiple classes You can add new classes without replacing older ones by using the += operator. This works by keeping older classes and adding new ones. **Note:** When adding a class, make sure to add a space `" "` before the class name. Let’s modify the existing example to see how it works. #### HTML Code: ``` Code language: JavaScript (javascript) ``` #### CSS code: ``` Code language: JavaScript (javascript) ``` #### Javascript code: ``` Code language: JavaScript (javascript) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151942/1-3.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151944/2-1.jpeg) ### Getting the class name Using the `.className` property, we can also retrieve the class names of the paragraph elements having `id = "para"`. #### HTML Code: ``` Code language: JavaScript (javascript) ``` #### Javascript Code: ``` Code language: JavaScript (javascript) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14154724/1-2-1.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14154726/2-2.jpeg) ## Using .classList.add() method In HTML, the `.classList`property returns the DOMTokenList representation of the element’s class attribute. This `.classList` property has a `.add()` method that can be used to add a class name to an HTML element. Here is an example of how you would use `.add` method in Javascript: ``` HTMLelement.classList.add("new_class");Code language: CSS (css) ``` ### Examples We will use the same files as before and only change the CSS and Javascript. #### CSS Code: ``` Code language: CSS (css) ``` #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14155939/1-3-1.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14155942/2-3.jpeg) ### Adding multiple classes The add() method is also capable of adding multiple classes simultaneously. When adding multiple classes, separate the classes with a comma. #### CSS Code: ``` Code language: CSS (css) ``` #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14160701/1-4-1.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14160703/2-4-1.jpeg) ## Using .setAttribute() Method An element can be modified by adding an attribute using the `setAttribute` method in Javascript. Since classes are also element attributes, we can add them `setAttribute` method to add a class. There are two parameters required by this method, the *attribute’s name,* and its *value*. Here is an example of how we would use this method in Javascript: ``` HTMLelmeent.setAttribute('class', 'new_class');Code language: HTML, XML (xml) ``` ### Examples Let’s take the previous example and change some lines to see how it works: #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14180149/1-5.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14180150/2-5.jpeg) ### Adding multiple classes In order to add multiple classes to the same element, we can pass a list of multiple class names separated by spaces to the `setAttribute`method. #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14181113/1-6.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14181115/2-6.jpeg) ## Some Other Useful methods ### Deleting a class The `.classList` property also has a `remove()` method which allows you to delete a class from an HTML element. Syntax example: ``` HTMLelement.classList.remove("class_name")Code language: HTML, XML (xml) ``` ### Toggling a class Similarly, The `toggle()` method of `classList` property can be used to toggle a class in javascript. Syntax example: ``` HTMLelement.classList.toggle("class_name")Code language: HTML, XML (xml) ``` ## Conclusion We just discussed how to add classes to elements. These properties allow you to add single or multiple classes to an element. You can also add a class when the element is hovered by using the `onmouseover` event. I hope this article explained everything you need to know about adding class names to HTML elements. If you ever feel lost and want help understanding where to start your coding journey, there are amazing courses and blogs for web development and other coding concepts on [Codedamn](https://codedamn.com/news). Remember to practice coding on a daily basis. You can play around with your code on Codedamn’s online [compiler](https://codedamn.com/playgrounds) as well. Finally, If you are interested in my content and would like to connect, then you can find me on [Linkedin](https://www.linkedin.com/in/indrakant-dana/) or [Twitter](https://twitter.com/its_ikD). Thank You for reading\! Sharing is caring Did you like what Indrakant wrote? Thank them for their work by sharing it on social media. Share ## No comments so far Curious about this topic? Continue your journey with these coding courses: [![Course thumbnail for JavaScript from Zero to Hero with 5+ projects](https://wsrv.nl/?url=https%3A%2F%2Fs3.us-east-1.amazonaws.com%2Fcreator-assets.codedamn.com%2Fdineshlg-6400c10a7195d7001409d219%2FCOURSE_IMAGE%2F2023-03-21%2F8dd3e8f8ce066ebac34568fb081a930aa66cbda8&w=256&q=82&output=webp) 4.5 169 students learning ![Photo of DINESH KUMAR REDDY](https://wsrv.nl/?url=https%3A%2F%2Fs3.us-east-1.amazonaws.com%2Fcreator-assets.codedamn.com%2Fdineshlg-6400c10a7195d7001409d219%2FPROFILE_PICTURE%2F2024-02-25%2F1ae8958b8a6303f4b3128a9dd87759bdcad81ae1&w=96&q=82&output=webp) DINESH KUMAR REDDYJavaScript from Zero to Hero with 5+ projects](https://codedamn.com/learn/javascript-with-real-world-projects) [![Course thumbnail for Mastering Advanced JavaScript](https://wsrv.nl/?url=https%3A%2F%2Fs3.us-east-1.amazonaws.com%2Fcreator-assets.codedamn.com%2Funwiredlearning-64d22d01a9b745000d38e131%2FCOURSE_IMAGE%2F2023-09-06%2F3a24322329a9579d83c085ffc029bd589855a26e&w=256&q=82&output=webp) 4.8 159 students learning ![Photo of Shubham Sarda](https://wsrv.nl/?url=https%3A%2F%2Fs3.us-east-1.amazonaws.com%2Fcreator-assets.codedamn.com%2Funwiredlearning-64d22d01a9b745000d38e131%2FPROFILE_PICTURE%2F2023-08-08%2F479daa37d7c56a1128a1c04993eba6544d265887&w=96&q=82&output=webp) Shubham SardaMastering Advanced JavaScript](https://codedamn.com/learn/mastering-advanced-javascript) [![Course thumbnail for Object Oriented Programming in JavaScript ](https://wsrv.nl/?url=https%3A%2F%2Fs3.us-east-1.amazonaws.com%2Fcreator-assets.codedamn.com%2Fkrishna216-64783f40cf3e83000dd66b68%2FCOURSE_IMAGE%2F2023-12-02%2Ffbd273baa385365cee1f975065b5fe7c04f4d442&w=256&q=82&output=webp) 4.7 ![Photo of Prod Code Tech](https://wsrv.nl/?url=https%3A%2F%2Fs3.us-east-1.amazonaws.com%2Fcreator-assets.codedamn.com%2Fkrishna216-64783f40cf3e83000dd66b68%2FPROFILE_PICTURE%2F2023-11-16%2F03dc6316c048ecd4353b73d5632042c90aabbfd8&w=96&q=82&output=webp) Prod Code TechObject Oriented Programming in JavaScript](https://codedamn.com/learn/object-oriented-programming-javascript) [Explore more](https://codedamn.com/explore) Footer Learn to code interactively - without ever leaving your browser. [Facebook](https://www.facebook.com/codedamncom/) [Instagram](https://www.instagram.com/codedamn/) [Twitter](https://twitter.com/codedamncom) [GitHub](https://github.com/codedamn/core) [YouTube](https://www.youtube.com/codedamn) [Discord](https://discord.com/invite/brtAY92J2r) Solutions - [Fermion - Build your online business](https://fermion.app/) - [Learning paths](https://codedamn.com/learning-paths) - [Explore platform](https://codedamn.com/explore) - [AI](https://codedamn.com/ai) - [Playgrounds (IDE)](https://codedamn.com/playgrounds) - [Codedamn Business](https://business.codedamn.com/) Resources - [Pricing](https://codedamn.com/pricing) - [Developer blog](https://codedamn.com/news) - [Online compilers](https://codedamn.com/online-compiler) - [Online web tools](https://codedamn.com/tool) Company - [About](https://codedamn.com/about) - [Support](https://codedamn.com/contact) - [Terms of Service](https://codedamn.com/terms-of-service) - [Privacy Policy](https://codedamn.com/privacy-policy) - [Feedback](https://codedamn.com/contact) Popular - [How to install NVM?](https://codedamn.com/news/nodejs/nvm-installation-setup-guide) - [How much JS before React?](https://codedamn.com/news/reactjs/react-prerequisites-javascript) - [React.js online compiler](https://codedamn.com/online-compiler/reactjs) - [Python online IDE](https://codedamn.com/online-compiler/python) - [Next.js best practices](https://codedamn.com/news/nextjs/next-js-best-practices) - [Teachable Alternatives](https://codedamn.com/news/product/7-best-teachable-alternatives-in-2024-for-content-creators) - [Solidity online compiler](https://codedamn.com/online-compiler/solidity) - [Golang online compiler](https://codedamn.com/online-compiler/go) - [Top Udemy Alternatives](https://codedamn.com/news/product/best-udemy-alternatives-for-instructors-in-2024) © Codedamn™ 2026. All rights reserved.
Readable Markdown
Javascript is one of the key elements behind adding interactivity to a website. Without it, thinking of creating a fully interactive and functional website is next to impossible. Among the many amazing features of this language is the variety of functions and methods it offers to make a developer’s life easier and more convenient. Using javascript, we can modify DOM elements or perform calculations behind the scenes while static HTML is displayed. The goal of this tutorial is to demonstrate in-depth how Javascript can be used to add classes to HTML elements and perform a number of other useful operations with its help. With that being said, let’s begin\! ## Introduction CSS uses the **class** attribute to perform a series of actions on elements with the same class name. **DOM** (Document Object Model) is a method of manipulating HTML documents. Javascript allows you to add classes to the body of your webpage through `document.body` or `document.getElementById("id")`. Classes can either be added directly to an HTML element as an attribute (Ex: `<p class="para-class">`) or by using JavaScript (which is what we’ll look at in this section). There are three different ways to add classes to an element using javascript. Let’s explore each of those approaches one by one. ## Using .className property The `.className`property can be used to set the name of the class of an element. Using this property, we can add a single class or multiple classes to an HTML element without replacing its existing classes. In addition, this property can also be used to return an element’s class attribute value. Syntax to set the class name: ``` HTMLelement.className = "new_class";Code language: HTML, XML (xml) ``` In this case, “`new_class`” specifies the element’s class name. We can add multiple classes by separating their names with spaces, for instance, “`new_class1 new_class2`“. To return the class name/names: ``` HTMLelement.className;Code language: HTML, XML (xml) ``` The property returns a string type representing a class or lists of classes of elements separated by space. ### Example Below is an example, that uses the `.className` property to add the class ***“***`new-para-class`***“*** to the paragraph element having id ***“***`para`***“***. The CSS is applied to the corresponding paragraph using the class name ***“***`new-para-class`***“***. In order to see the effect, we need to click the given HTML button **“**`Add New Class`**“** to see the effect. **Note**: If you assign a class name directly to the `className` property, the existing classes will be overwritten. #### HTML Code: ``` Code language: HTML, XML (xml) ``` #### CSS Code: ``` Code language: CSS (css) ``` #### Javascript Code: ``` Code language: JavaScript (javascript) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151007/1-2.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151010/2.jpeg) ### Adding multiple classes You can add new classes without replacing older ones by using the += operator. This works by keeping older classes and adding new ones. **Note:** When adding a class, make sure to add a space `" "` before the class name. Let’s modify the existing example to see how it works. #### HTML Code: ``` Code language: JavaScript (javascript) ``` #### CSS code: ``` Code language: JavaScript (javascript) ``` #### Javascript code: ``` Code language: JavaScript (javascript) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151942/1-3.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14151944/2-1.jpeg) ### Getting the class name Using the `.className` property, we can also retrieve the class names of the paragraph elements having `id = "para"`. #### HTML Code: ``` Code language: JavaScript (javascript) ``` #### Javascript Code: ``` Code language: JavaScript (javascript) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14154724/1-2-1.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14154726/2-2.jpeg) ## Using .classList.add() method In HTML, the `.classList`property returns the DOMTokenList representation of the element’s class attribute. This `.classList` property has a `.add()` method that can be used to add a class name to an HTML element. Here is an example of how you would use `.add` method in Javascript: ``` HTMLelement.classList.add("new_class");Code language: CSS (css) ``` ### Examples We will use the same files as before and only change the CSS and Javascript. #### CSS Code: ``` Code language: CSS (css) ``` #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14155939/1-3-1.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14155942/2-3.jpeg) ### Adding multiple classes The add() method is also capable of adding multiple classes simultaneously. When adding multiple classes, separate the classes with a comma. #### CSS Code: ``` Code language: CSS (css) ``` #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14160701/1-4-1.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14160703/2-4-1.jpeg) ## Using .setAttribute() Method An element can be modified by adding an attribute using the `setAttribute` method in Javascript. Since classes are also element attributes, we can add them `setAttribute` method to add a class. There are two parameters required by this method, the *attribute’s name,* and its *value*. Here is an example of how we would use this method in Javascript: ``` HTMLelmeent.setAttribute('class', 'new_class');Code language: HTML, XML (xml) ``` ### Examples Let’s take the previous example and change some lines to see how it works: #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14180149/1-5.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14180150/2-5.jpeg) ### Adding multiple classes In order to add multiple classes to the same element, we can pass a list of multiple class names separated by spaces to the `setAttribute`method. #### Javascript Code: ``` Code language: PHP (php) ``` #### Output: To view the HTML output before and after clicking the button, slide towards the left and right respectively. ![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14181113/1-6.jpeg)![](https://codedamn-blog.s3.amazonaws.com/wp-content/uploads/2022/09/14181115/2-6.jpeg) ## Some Other Useful methods ### Deleting a class The `.classList` property also has a `remove()` method which allows you to delete a class from an HTML element. Syntax example: ``` HTMLelement.classList.remove("class_name")Code language: HTML, XML (xml) ``` ### Toggling a class Similarly, The `toggle()` method of `classList` property can be used to toggle a class in javascript. Syntax example: ``` HTMLelement.classList.toggle("class_name")Code language: HTML, XML (xml) ``` ## Conclusion We just discussed how to add classes to elements. These properties allow you to add single or multiple classes to an element. You can also add a class when the element is hovered by using the `onmouseover` event. I hope this article explained everything you need to know about adding class names to HTML elements. If you ever feel lost and want help understanding where to start your coding journey, there are amazing courses and blogs for web development and other coding concepts on [Codedamn](https://codedamn.com/news). Remember to practice coding on a daily basis. You can play around with your code on Codedamn’s online [compiler](https://codedamn.com/playgrounds) as well. Finally, If you are interested in my content and would like to connect, then you can find me on [Linkedin](https://www.linkedin.com/in/indrakant-dana/) or [Twitter](https://twitter.com/its_ikD). Thank You for reading\!
Shard54 (laksa)
Root Hash254754527753975654
Unparsed URLcom,codedamn!/news/javascript/how-to-add-class-to-element s443