DEV Community

Cover image for Changing Classes
GiandoDev
GiandoDev

Posted on

Changing Classes

Add Class

Alt Text
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.
Alt Text

Remove Class

Alt Text
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

Alt Text
Sometimes we need to check if a class is present and, if It is, we perform same tasks.

Toggling

Alt Text
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)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

el.classList.removeClass('novice'); el.classList.addClass('ninja')