Hemanth's Scribes

web

Class Handling With classList

Author Photo

Hemanth HM

Thumbnail

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

element with class=“foo bar”. p.classList.remove(“foo”); p.classList.add(“cat dog”);

// if visible is set remove it, otherwise add it. p.classList.toggle(“visible”);

// Will return true. console.log(div.classList.contains(“foo”));

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”)

#javascript#linux
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.