Using the Element classList to manage classnames in HTML5January 19, 2016
If you didn’t use jQuery you would have to use setAttribute which makes perfect sense and is easy to use. The problem comes when you want to add more classes to your element. Adding is easy, you retrieve the class string with getAttribute and then concatenate the classnames you which to add. Fairly easy but not very intuitive to use and if you only want to remove a classname then you have to either use a regular expression or split the string on the space character and check against the classname value and then re-concatenate the string. To remove all classnames you would just remove the class attribute all together.
Looking closer at the DOMTokenList and comparing it with the functionality that jQuery provides for working with classes you’ll find them almost identical. The information below is taken from Mozilla Developer Network and I think it speaks for itself. Using the
length property and the methods
item, contains, add, remove and toggle makes it very easy to work with element classnames without using jQuery or writing a lot of glue code functions.
DOMTokenList.length //Read only, is an integer representing the number of objects stored in the object. DOMTokenList.item() //Returns an item in the list by its index (or undefined if the number is greater than or equal to the length of the list, prior to Gecko 7.0 returned null) DOMTokenList.contains() //Returns true if the underlying string contains token, otherwise false DOMTokenList.add() //Adds token to the underlying string DOMTokenList.remove() //Removes token from the underlying string DOMTokenList.toggle() //Removes token from string and returns false. If token doesn't exist it's added and the function returns true