Add Class
When we use the querySelector() method and after we have to use classList property it is easy to make the mistake of adding "."
We may add multiple classes in the same time but we don't need to do this.
To be sure that we have added properly the class we may check in our elements inside our inspector if the class is present.
Remove Class
If we have to remove a class from an element, we simply replace add with remove. In this case we may also remove multiple elements at the same time but we still don't need to perform this.
Checking
Sometimes we need to check if a class is present and, if It is, we perform same tasks.
Toggling
Often we have to toggle a class. We may remove or add a class with if/else statements but with toggle method is more simple and coincise. Like in the example above toggle checks automatically if a class exists and if it exists, remove it else add is.
Super simple and usefull.
More about classList here: MDN
Top comments (1)
el.classList.removeClass('novice'); el.classList.addClass('ninja')