It was always difficult to manage classes of HTML elements using JavaScript, therefore developer depended on jQuery class management function to manipulate classes. But now the new classList API makes manipulation of classes easy in JavaScript.
Let’s see the different functions belonging to classList API:
classList property
classList property of HTML elements is the heart of classList API. It exposes all the classList API functions.
add()
add() function is used to add a new class to the HTML element.
remove()
remove() is used to remove a class.
toggle()
Sometimes we need to add or remove a class name based on a user interaction or the state of the site. This is done using the toggle() method
item()
The classList API provides a method for retrieving class names based on it’s position in the list of classes.
length
length property returns the total number of classes attached to the element.
contains()
contains() is used to check if a class exists in a element or not.
toString()
It returns class list as a string.
Old Browser Support
Very old browsers don’t support classList API therefore use the classList Polyfill.
Leave a Reply