How to Add a Class to a Given Element

The class name attribute is used to manage tasks for elements with the specified class name. If you want to create a JavaScript function that will add a class to the <div> element, there are some methods of doing it in JavaScript.

The .className property

The className property of the Element interface is used for getting and setting the value of the given element's class attribute.

First, put an id on the element to get a reference:

<div id="divId" class="someClass">
  <p>Add new classes</p>
</div>

Then use the .className to add a class:

<!DOCTYPE html>
<html>
  <body>
    <div id="divId" class="someClass ">
      <p>Add new classes</p>
    </div>
    <script>
      let cName = document.getElementById("divId");
      cName.className += "otherClass";
      alert(cName.className);
    </script>
  </body>
</html>
It’s important to include the space before “someclass”, otherwise it compromises the existing classes coming before it in the class list.

The .add() method

The add() method of the DOMTokenList interface is used to add the given token to the list. This method is also used to add a class name to the specified element.

<!DOCTYPE html>
<html>
  <body>
    <div id="divId" class="someClass ">
      <p>Add new classes</p>
    </div>
    <script>
      function addClass() {
        let cName = document.getElementById("divId");
        cName.classList.add("addNewClass");
        alert(cName.classList);
      }
      addClass();
    </script>
  </body>
</html>