Handling classes of DOM Element in JavaScript

June 20, 2020

Consider we have a div with 3 span

<div class="class1 class2" id="item">

The detail of classes of DOM elements are stored in classList property. The classList is a DOMTokenList(array-like object) which contains all the class of the element.

let ele = document.getElementById('item');

let list = ele.classList;

for(let className of list){


There are some in-build methods you can use to manipulate the class of the Element

Method Description
add add a class to the list
remove remove class name
contains check if the class present
toggle Toggle the class(add a class if not present, remove if already present)
item get class name based on index

1. add

Adding class to the element

let item = document.getElementById('item');

console.log(...item.classList); // class1 class2 class3

Adding multiple class

item.classList.add('class4', 'class5');

2. remove

Remove a class if it is available otherwise, nothing happens


// removing multiple class

item.classList.remove('class3', 'class5');

3. contains

The contains method returns true if the classList contains a passed class, otherwise returns false.

console.log(...item.classList); // class1 class2

item.classList.contains('class1'); // true
item.classList.contains('class5'); // false
item.classList.contains(); // throws error atleast pass single string

4. toggle

The toggle method will add the class name if the class name already not available. It removes the class name if the class is already available.

console.log(...item.classList); // class1 class2
item.classList.toggle('new_class'); // adds new_class
item.classList.toggle('new_class_2'); // adds new_class_2
console.log(...item.classList); // class1 class2 new_class new_class_2

item.classList.toggle('new_class_2'); // remove the new_class_2

The toggle method returns true, if the class is added. If the class is removed then the toggle method returns false

classList.toggle optionally takes a second argument(boolean). If you pass

  • true - force add a class(if the class already present no action preformed)
  • false - force remove a class(if the class already not available no action preformed )

5. item

item method will return the class name based on index passed, null will be returned if no item available in the index

console.log(...item.classList); // class1 class2 new_class
item.classList.item(0); // class1
item.classList.item(1); // class2

// if no item available then null is returned
item.classList.item(5); // null

Please donate here, for making more tutorials.