Using classList() API in JavaScript to work with multiple classes for a HTML element.

For training and consulting, write to us at info@xrmforyou.com

Today I would like to show you the cool classList API which exists in the native JavaScript API but trust me, so many of us are still not aware of it.
Event I find people with somewhat significant experience of working with JavaScript is not aware of the same.
Well the classList() API allows you to manipulate multiple classes on a HTML element. Let’s try some demo here.
Let’s say we have a HTML div element with id – “main_div”. And you want to add multiple classes to the div element. Let’s see how you can work with those classes using classList() API.

const ele = document.querySelector(“#main_div”);
// You can add many classes here.
ele.classList.Add(“class1”, “class2”, “class3”);

While that’s nice, what’s even cool is the fact you can toggle classes using the toggle method of classList API.

// Remove a class
ele.toggle(“class1”, false);
// add a class
ele.toggle(“class1”, true);

Quite a cool and handy class to learn.
Hope this helps!
Debajit Dutta
(Microsoft MVP)