How to add a class to a given element in Javascript

Add a class to a given element in Javascript. The class name property is used to control the tasks for elements with the defined class name. If you want to perform a JavaScript function that will add a class to an element, there are some ways of doing it in JavaScript.

.className property in javascript

The className attribute 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:

<!DOCTYPE html>
<html>
  <body>
    <div id="softId" class="softClass ">
      <p>Added new classes</p>
    </div>
    <script>
      let className = document.getElementById("softId");
      className.className += "otherClass";
      alert(className.className);
    </script>
  </body>
</html>

The className property is supported in all modern browsers.

Leave a Reply

Your email address will not be published. Required fields are marked *