Let’s understand the HTML DOM classList Property first.
HTML DOM classList Property
You can use this property to get class names of an HTML elements. It returns a DOMTokenList object.
classList Property is helpful to set, get, remove or even toggle the class names of an element.
Syntax
let el = document.getElementById('xyz');
let allClasses = el.classList;
//do something with it
To add or remove or do anything else with the classes, we need to get the element first. Here are all the methods we can use to get the HTML element in the DOM.
The HTML DOM classList Property is read-only but there is a way to modify it using the add() and remove() methods.
The classList property does not work in IE9 and earlier versions but we can use className property instead.
Examples
How to add a class to an element?
let el = document.getElementById('xyz');
el.classList.add("class1");
👎 If the class already exists and you still try to add it then it won’t be added again. You must use a different name.
How to add multiple classes to an element?
let el = document.getElementById('xyz');
el.classList.add("class2", "class3");
How to remove a class from an element?
let el = document.getElementById('xyz');
el.classList.remove("class1");
If the class doesn’t exists but you still try to remove it then it won’t give you any error. Your request will be ignored.
How to remove multiple classes from an element?
let el = document.getElementById('xyz');
el.classList.remove("class2", "class3");
How to toggle between two classes for an element?
let el = document.getElementById('xyz');
el.classList.toggle("class4");
How to get class names of an element?
let el = document.getElementById('xyz');
let elClasses = el.classList;
// do something with elClasses
It will return an empty DOMTokenList if there are no classes.
How to get the total number of classes an element has?
let el = document.getElementById('xyz');
let elTotalClasses = el.classList.length;
// do something with elTotalClasses
It will return 0 if there are no classes.
How to get the first class name of an element?
let el = document.getElementById('xyz');
let elFirstClass = el.classList.item(0);
// do something with elFirstClass
ℹ Just change the index in the item() method to get class indexed at another position.
👉 It will return null if the index is out of range.
How to check if an element has a particular class?
let el = document.getElementById('xyz');
let elHasClass = el.classList.classList.contains("abc");;
// will return either true or false
basics classList DOM html property toggle