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

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (1)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️