How 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">
  <img ... id="img1" name="img1" />

Then use the .className to add a class:

var cName = document.getElementById("divId");
cName.className += "otherClass";
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.

function addClass({
    var cName = document.getElementById("p");

Do you find this helpful?

Related articles