DEV Community

Cover image for Changing Classes
GiandoDev
GiandoDev

Posted on

1 1

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

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay