How to add and remove multiple CSS classes simultaneously from a DOM node

My very bad inking skills trying to create a medium blog post worthy image. I used a Faber-Castell fountain pen and Waterman Havana brown ink as only cool boys write with brown inks 🤣

Hello folks, here we are with another short story from the frontend world. We are going to learn how to add and remove multiple CSS classes from a DOM node, in our case a div.

The boring way 🤢

To add a CSS class all you have to do is to add some string with the class name on the node inside the value of the class attribute. Basically here:

Now, to do this, we will be using a special method called setAttribute. Let’s assume we have the DOM node saved in the myNode variable.

But that looks a bit ugly and what about when we need to add another CSS class? Oh bummer!

Adding a second CSS class in this fashion will replace the previous class which is not exactly what we are looking for. Of course, you may say that we can get the CSS string first, append another class name to it and then set it back. Something like this:

That would do the job but it looks a bit clumsy and there is a better, cooler and native way to handles CSS classes in JavaScript. Let me introduce you to this beautiful DOM node method called classList.

The cool way 😜

With classList we rock like a boss 😂. Let me show you.

What about when we have an array of classes to add? Let’s see:

Brillante! Oleeee! Applause please 👏
Now let’s remove a class. Probably you guessed already. There is an equivalent method, similar to the add one called remove. To remove a class we do like this:

Now let’s wrap everything we learned today in a nifty blazing fast function so we can reuse it many times. Shall we? Let’s call our utility tool css and we implement the option to add and remove css classes in one go. For example let’s assume we have an object with classes that we wanna add and remove. Let’s assume true is for adding a class and false is for removing one. Something like this:

Now let’s assume we have a node with two classes, alpha and charlie and we want to remove them and add other two classes: bravoand delta. So the div will become from:

to:

Ok, ok, enough talking. Show me the 🧀

Examples and source code

The magic code. Open the sandbox so you don’t have to struggle reading the code inside this tiny box 😜

I fly and code for fun

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store