Photo by SLON V KASHE on Unsplash

Javascript — Swap classes of an HTML element

Recently I came across the problem, that I had to programmatically change a div’s color from red to green. Sounds simple and it’s actually quite simple if you know your JavaScript.

jQuery contains a function called “toggleClass()” that swaps class attributes in and out of an element. I looked for a similar function in ES6 but couldn’t find one. Florian Brinkmann (@FloBrinkmann) pointed me to “classList.toggle()” which does exactly the thing I’m looking for (it’s hidden in the “Examples” passage).

Here’s the simple solution to my problem:

The jQuery implementation contains the ability to define more than two classes to add or remove from the element. Using a new ES6 element (the spread operator) this can be implemented like this:

jQuery’s “toggleClass()” has some more functionality available but currently I don’t have any need for it. For a start this is enough.

Long time WordPress Plugin developer. Nowadays I more often code JavaScript frontends and Chrome extensions. Blog:

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