W3docs

How to Change an Element’s Class with JavaScript

One of the most common issues in JavaScript is changing an element’s class. In this snippet, we are going to show you the efficient ways of achieving it.

In this tutorial, you will learn the ways of changing an element’s class with JavaScript.

In JavaScript, the standard way of selecting an element is to use the <kbd class="highlighted">document.getElementById("Id")</kbd>. Of course, it is possible to obtain elements in other ways, as well, and in some circumstances, use this.

For replacing all the existing classes with a single or more classes, you should set the className property, as follows:

javascript selecting an element getElementById

document.getElementById("My_Element").className = "My_Class";

For adding a class to an element, without affecting/removing existing values, you should append a space and a new classname, like here:

javascript adding a class to an element getElementById

document.getElementById("My_Element").className += " My_Class";

For removing a single class from an element, without affecting other potential classes, a regular expression replace is needed, like here:

javascript removing a single class from an element getElementById

document.getElementById("My_Element").className = document.getElementById("My_Element").className.replace(/(?:^|\s)My_Class(?!\S)/g, '') // Code wrapped for readability above is all one statement

The explanation of this regular expression is the following:

javascript regular expression

(?:^|\s)   # Match the start of the string, or any single whitespace character
My_Class   # The literal text for the classname to remove
(?!\S)     # Negative lookahead to verify the above is the whole classname
           # Ensures there is no non-space character following
           # (i.e. must be end of string or a space)

The flag <kbd class="highlighted">g</kbd> commands the replacement to repeat as required if the class name has been added several times.

The <kbd class="highlighted">regex</kbd> that is used above can also be applied for checking whether a specific class exists.

For instance:

javascript regular expression

if(document.getElementById("My_Element").className.match(/(?:^|\s)MyClass(?!\S)/))

Note: In modern JavaScript, the classList API is the standard and recommended approach for class manipulation. It avoids string parsing issues and provides built-in methods like add(), remove(), and toggle(). For example: element.classList.remove('My_Class');

While it is possible to directly write JavaScript in the HTML event attributes, (for instance, <kbd class="highlighted">onclick="this.className+=' My_Class'"</kbd>), this practice is discouraged. Particularly on larger applications, a more sustainable code is reached by separating HTML markup from the JavaScript interaction logic.

The first step to reach this is creating a function and calling it in the onclick attribute, like here:

javascript creating function

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style type="text/css">
      body {
        text-align: center;
      }
      .oldClassName {
        background-color: green;
      }
      .newClassName {
        background-color: blue;
      }
      .pId {
        margin-top: 30px;
      }
      #buttonId {
        padding: 15px;
      }
    </style>
  </head>
  <body>
    <h2>Change class name</h2>
    <button class="oldClassName" id="buttonId" onclick="changeClass()">Click on Button</button>
    <br />
    <p id="pId">Old class name: oldClassName </p>
    <script type="text/javascript">
      function changeClass() {
        document.getElementById('buttonId').className = "newClassName";
        let button_class = document.getElementById('buttonId').className;
        document.getElementById('pId').innerHTML = "New class name: " + button_class;
      }
    </script>
  </body>
</html>

The second step is moving the onclick event out of HTML and into JavaScript by using <kbd class="highlighted">addEventListener</kbd>, as follows:

javascript addEventListener

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style type="text/css">
      body {
        text-align: center;
      }
      .oldClassName {
        background-color: green;
      }
      .newClassName {
        background-color: blue;
      }
      .pId {
        margin-top: 30px;
      }
      #buttonId {
        padding: 15px;
      }
    </style>
  </head>
  <body>
    <h2>Change class name</h2>
    <button class="oldClassName" id="buttonId">Click on Button</button>
    <br />
    <p id="pId">Old class name: oldClassName </p>
    <script type="text/javascript">
      function changeClass() {
        document.getElementById('buttonId').className = "newClassName";
        let button_class = document.getElementById('buttonId').className;
        document.getElementById('pId').innerHTML = "New class name: " + button_class;
      }
      window.onload = function() {
        document.getElementById("buttonId").addEventListener('click', changeClass);
      }
    </script>
  </body>
</html>

You can also change classes by using jQuery, as follows:

javascript change classes

$('#My_Element').addClass('My_Class');
$('#My_Element').removeClass('My_Class');
if ($('#My_Element').hasClass('My_Class'))

Additionally, jQuery can provide a shortcut for adding a class, in case it doesn’t apply, either removing a class, which does it, like here:

javascript toggle classes

$('#My_Element').toggleClass('My_Class');

Also, you have the option of assigning a function to a click event using jQuery, as follows:

javascript click event function

$('#My_Element').click(changedClass);

or, without needing an id:

javascript click event function

$(':button:contains(Button)').click(changedClass);

Describing the Regular Expressions

Regular expressions (RegExp) are patterns that are applied for matching character combinations in <kbd class="highlighted">strings</kbd>. They are also considered objects in JavaScript. They are used along with the exec and test methods of <kbd class="highlighted">RegExp</kbd>, as well as with the replace, match, search and split methods of String.

The regular expressions obtain four optional flags that might be used either independently or together in any sequence and are included as part of the regular expression.