Quick intro to JavaScript CSS ClassLIst API

Of all the ways people have been using jQuery, one of the methods that rank high up there is jQuery's CSS class manipulation methods, which are:


These functions make it extremely easy to add, remove, and check whether an element has a particular CSS class.

Well, all modern browsers now allow you to do away with jQuery for duplicating the above functions. The classList API is pretty self explanatory. See the below:

el.classList.add("myclass") //adds a class to element
el.classList.add("class1", "class2", etc) //add more than 1 CSS classes
el.classList.remove("myclass") //removes a class from element
el.classList.remove("class1", "class2", etc) //removes multiple CSS classes
el.classList.toggle("myclass") //toggles a class. If already exists removes and returns false. Otherwise adds class and returns true
el.classList.toggle("myclass", expression) // adds or removes "myclass" based on outcome of expression. Not supported in IE11 or FF26 or less.
el.classList.contains("myclass") // check if the a class is present inside the element