How to add another Class name to an element using JavaScript

← PrevNext →

Let us assume, I have a <div> element and it has a class name assigned to it using CSS (at design time). Later, while executing a process, I want to add another class name to the <div> element dynamically. There is a simple method that you can use in JavaScript to do this.

An element can have more than one class name (css class) attached to it. For example,

<!--   DIV having multiple class names -->
<div class='class1 class2'>
    Hello World :-)
</div>

The CSS will look like...

<style>
  .class1 {
    padding: 10px;
    border: solid 1px red;
  }
  
  .class2 {
    font-family: Corbel;
    font-size: 18px;
  }
</style>

Now assuming, I have only one class name assigned to the DIV at design-time like this,

<div class='class1'>
    Hello World :-)
</div>

and later, I want to add or assign the second class name at runtime using JavaScript.

To do this, I can use the .classList property.

Add another Class name to an Element using .classList Property

The ".classList" property provides two important methods, .add() and .remove(). I'll use the add() method to add another class name to the element.

Note: You can use the ".remove()" method to remove a class name from the element.

<head>
<style>
  * { font-family: Corbel; }
  
  .class1 {
    padding: 10px;
    border: solid 1px red;
    cursor: pointer;
  }

  .class2 {
    font-family: Verdana;
    font-size: 18px;
  }
</style>
</head>
<body>
  <div class='class1'>
    Hello World :-)
  </div>
</body>
<script>
    window.addEventListener('click', function (e) {
        e.target.classList.add('class2');
    })
</script>
Try it

Check the element's properties in the console window before and after clicking the element. Before you click the element, the DIV will have one class name. After the click, JS code will add another class name to it.

Also remember, you can using add() method to add "multiple" class names to an element. For example,

e.target.classList.add('class2', 'class3');

← PreviousNext →