DEV Community

Cover image for JS: How to add or remove a class and make your sites interactive
Lorenzo
Lorenzo

Posted on • Edited on

6 4

JS: How to add or remove a class and make your sites interactive

Hello World! New episode of the series - A CSS/JS trick in 5 minutes.
Today we will quickly see how to manipulate a class throw javascript (add, remove and check presence).


In reality, you have to imagine classes as a list, all elements in a page have is own list of class you can modify with javascript. So if you want to modify an element you don't need to do all the stuff (it's much longer and boring) with javascript. You just have to define a class in CSS with all the attributes then add this class to the element(s) you want to modify. So for example you can have a live element update on scrolling

Add

  let foo = document.querySelector("#foo");
  element.classList.add("newClass");
Enter fullscreen mode Exit fullscreen mode

Remove

 foo.classList.remove("classToRemove");
Enter fullscreen mode Exit fullscreen mode

You can also check if an element contains a class (and then perform operations with the boolean result):

  foo.classList.contains('AreYouHere')
Enter fullscreen mode Exit fullscreen mode

Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue :)

Check this article about how to write CSS like a pro!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay