{"id":1519,"date":"2024-01-25T13:00:00","date_gmt":"2024-01-25T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1519"},"modified":"2024-01-29T16:26:35","modified_gmt":"2024-01-29T16:26:35","slug":"add-class-to-element-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/add-class-to-element-javascript\/","title":{"rendered":"Adding a Class to an Element in JavaScript (with code)"},"content":{"rendered":"\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>4 Methods to Add a Class to an Element Using JavaScript<\/strong><\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>Let\u2019s check out the four different methods to add a class to an element using JavaScript along with examples:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1) Using .className Property<\/strong><\/h3>\n\n\n\n<p><strong>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.<\/strong><\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Get the element by its ID\nvar myElement = document.getElementById('myElement');\n\n\/\/ Add a class to the element using className\nmyElement.className += ' newClass';<\/pre><\/div>\n\n\n\n<p>Here myElement refers to the HTML element to which we want to add the class, and \u201cnewClass\u201d is the name of the class we want to add.<\/p>\n\n\n\n<p>If we want to add multiple classes together we can simply add them using spaces:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Get the element by its ID\nvar myElement = document.getElementById('myElement');\n\n\/\/ Add a class to the element using className\nmyElement.className += ' newClass1 newClass2 newClass3';<\/pre><\/div>\n\n\n\n<p>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\u2019s the code:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Get the element by its ID\nvar myElement = document.getElementById('myElement');\n\n\/\/ Add a class to the element using className\nmyElement.className = ' newClass';<\/pre><\/div>\n\n\n\n<p>While using +=, we are appending a class to existing classes by concatenating classes. If we do not add a space before \u2018newClass\u2019, then we will join two class names and this will lead to unintended results:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text\/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;HTML&quot;,&quot;modeName&quot;:&quot;html&quot;}\">&lt;body&gt;\n\n    &lt;!-- An example element with an ID and an existing class --&gt;\n    &lt;div id=&quot;myElement&quot; class=&quot;existingClass&quot;&gt;This is a sample element.&lt;\/div&gt;\n\n    &lt;script&gt;\n        \/\/ Get the element by its ID\n        var myElement = document.getElementById('myElement');\n\n        \/\/ Add a class without a space using className\n        myElement.className += 'newClass';\n    &lt;\/script&gt;\n\n&lt;\/body&gt;<\/pre><\/div>\n\n\n\n<p>Here, the original class of the element is \u2018existingClass\u2019, and we attempt to add a new class named \u2018newClass\u2019 without a space before it. The result will be that the classes are concatenated without a space, leading to a single combined name(\u2018existingClassnewClass\u2019).&nbsp;&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2) Using classList.add() Method<\/strong><\/h3>\n\n\n\n<p>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.<\/p>\n\n\n\n<p> This method is preferred over manipulating \u2018className\u2019 directly because it is more explicit and doesn\u2019t replace existing classes.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Get the element by its ID\nvar myElement = document.getElementById('myElement');\n\n\/\/ Add a class to the element using classList.add()\nmyElement.classList.add('newClass');<\/pre><\/div>\n\n\n\n<p>Here myElement refers to the HTML element to which we want to add the class, and \u201cnewClass\u201d is the name of the class we want to add.<\/p>\n\n\n\n<p>If we want to add multiple classes together, we have to pass each class name as a separate argument to the \u2018add()\u2019 method. Here\u2019s an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Get the element by its ID\nvar myElement = document.getElementById('myElement');\n\n\/\/ Add multiple classes to the element using classList.add()\nmyElement.classList.add('class1', 'class2', 'class3');<\/pre><\/div>\n\n\n\n<p>In this example, the \u2018classList.add()\u2019 method is used to add three classes(\u2018class1\u2019, \u2018class2\u2019, and \u2018class3\u2019) to the element with the ID \u2018myElement\u2019.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3) Using setAttribute() Method<\/strong><\/h3>\n\n\n\n<p>Similar to the \u2018className\u2019 property, this method also replaces the entire class attribute, therefore causing unintended results. <\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>To add a class to an element using the setAttribute() method, we need to specify the attribute name as \u2018class\u2019 and the value as the name of the class we want to add. For example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Get the element by its ID\nvar Ele = document.getElementById('myElement');\n\n\/\/ Add a class to the element using className\nEle.className = 'previousClass';\n\n\/\/ Get the element by its ID\nvar myElement = document.getElementById('myElement');\n\n\/\/ Add a class to the element using setAttribute()\nmyElement.setAttribute('class', 'newClass');<\/pre><\/div>\n\n\n\n<p>Here, by using the setAttribute() method, the \u2018previousClass\u2019 of the element is replaced by \u2018newClass\u2019.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4) Using classList.toggle() Method<\/strong><\/h3>\n\n\n\n<p>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\u2019s not present and removes it if it&#8217;s present. <\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Get the element by its ID\nvar myElement = document.getElementById('myElement');\n\n\/\/ Toggle a class on the element using classList.toggle()\nmyElement.classList.toggle('active');<\/pre><\/div>\n\n\n\n<p>In this example, if the element initially has the class \u2018active\u2019, the toggle() method will remove it. If the element doesn\u2019t have the class \u2018active\u2019, the method will add it.&nbsp;<\/p>\n\n\n\n<p>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. <\/p>\n\n\n\n<p>Also, to make your code much better, you need to know <a href=\"https:\/\/favtutor.com\/articles\/link-javascript-html\/\">different ways to link HTML to JavaScript<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to add a class to an element in JavaScript using className, classList, toggle and setAttribute method, with examples.<\/p>\n","protected":false},"author":13,"featured_media":1522,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11],"class_list":["post-1519","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1519","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1519"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1519\/revisions"}],"predecessor-version":[{"id":1584,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1519\/revisions\/1584"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1522"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1519"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1519"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1519"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}