How to Change an Element’s Class with JavaScript

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 document.getElementById("Id"). 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 attribute, as follows:

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:

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

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

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:

( ? : ^ | \s) # Match the start of the string, or any single whitespace character MyClass       # 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 g commands the replacement to repeat as required if the class name has been added several times.

The regex that is used above can also be applied for checking whether a specific class exists.

For instance:

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

While it is possible to directly write JavaScript in the HTML event attributes, (for instance, onclick="this.className+=' My_Class'"), you are not welcomed to act so. 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:

<!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>Chenge 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 addEventListener, as follows:

<!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>Chenge 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:

$('#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:

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

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

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

or, without needing an id:

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

Describing the Regular Expressions

Regular expressions (RegExp) are patterns that are applied for matching character combinations in strings. They are also considered objects in JavaScript. They are used along with the exec and test methods of RegExp, 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.

Do you find this helpful?

Related articles