Class handling with classList

classList returns a token list of the class attribute for a given element, with which one can do the below easily!

  • add a class to an element's list of classes

  • remove a class from an element's list of classes

  • toggle the existence of a class in an element's list of classes

  • check if an element's list of classes contains a specific class

// p is an object reference to a <p> element with class="foo bar".
p.classList.add("cat dog");
// if visible is set remove it, otherwise add it.
// Will return true.

To check if the browser supports this API : if ( !("classList" in document.documentElement) ) {..} or

if (!!document.createElement('p').classList) {
 // native classList support

One can also check if an element has a class or not using  p.classList.length

Hope this is useful, it's been really useful for me so far!

Edit 0:

In jQuery :  $().toggleClass("active", true)

While the ClassList per se lacks that facility, one can do the same like :

elem.classList[boolean ? "add" : "remove"] ("active")

Share this