Tech blog to share information.

April 23, 2018

classList Api - Manipulating CSS classes Javascript Way

April 23, 2018 Posted by tjcool , , No comments
Javascript has been around from many years and its core of web development. Whether its Dom manipulation, validation or making ajax request, javascript is always there. But all those years we have not seen game changing changes in javascript and may be that is a reason client-side development of client-side framework started. We all know Jquery and understands why it becomes backbone of web development so quickly.

But, from last couple of years Html5 has brought super fun to javascript development by introducing new Api and classList is one of them.

What is classListApi ?

The classList API provides methods and properties to manage class names of DOM elements. Using it, we can perform operations such as adding and removing classes, or checking if a given class is present on an element. The classList API exposes these methods and properties via an attribute of the DOM element, called classList.
The Element.classList is a read-only property which returns a live DOMTokenList collection of the class attributes of the element.Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via “ element.className.”


const elementClasses = elementNodeReference.classList;


add( String [, String [, ...]] )

Simply supply the class you want to add as an argument to the add() method. If these classes already exist in attribute of the element, then they are ignored.

remove( String [, String [, ...]] )

Remove specified class values. Also if you try to removing a class that does not exist, it won’t throw any error.

toggle( String [, force] )

Toggle come with two flavors
  1. String (classname):  If class exists then remove it and return false, if not, then add it and return true.
  2. Force (True/False): If force is set to true, the class will be added but not removed. If it’s false, the opposite will happen — the class will be removed but not added.
div.classList.toggle("visible", i < 10 );

contains( String )

Checks if specified class value exists in class attribute of the element. This method returns a Boolean true or false when checking for the presence of a class in the list.It is very useful when you want to check if particular class exists or not.
if(div.classList.contains('class1') {
Complete classList Api Method List
classList Api Stackoverflow Discussions