Over the weekend, I finished the Learn Node video course by Wes Bos. It was a great course; but, one of the things that I love about watching video tutorials, like Learn Node, is that you pick up lots of little tid-bits that are only peripherally related to the topic at hand. For example, in one of the videos, I saw Wes adding and removing CSS classes using a .classList DOM (Document Object Model) property. Historically, I've used the .className DOM property to try and manipulate class names; but, using .classList looks so much easier. As such, I wanted to take a quick look at how it works.
With that said, the .classList Element property presents a token-list (ie, a space-delimited String) of the classes being applied to the Element. But, unlike the traditional .className property, the .classList property provides convenience methods for accessing and manipulating the individual classes in the .classList:
- .add( String )
- .remove( String )
- .contains( String )
- .item( Number )
NOTE: There are other methods on the .classList property that are less widely supported, like .toggle().
To see this in action, I've put together a small demo in which the user can add and remove classes to and and from a target element:
As you can see, the links in the demo add or remove the classes "one", "two", and "three". In the logic for the event-delegation-based click-handler, I'm using the .classList property in several ways:
- I'm checking to see if the click-target is one of the action links.
- I'm adding or removing the relevant class.
- I'm logging the resultant class list.
As you can see, using the .add(), .remove(), and .contains() convenience classes is much easier than trying to perform manual string manipulation on .className. And, when we run this demo and toggle a few classes, we get the following output:
As you can see, by using the .classList convenience methods - .add() and .remove() - we were able to add and remove individual classes without having to do any string manipulation.
Want to use code from this post? Check out the license.