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:

function toggleClass(element, className1, className2) {
                element
                    .classList
                    .toggle(className1);
                element
                    .classList
                    .toggle(className2)

            }

toggleClass(myDiv, 'red', 'green');

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:

 function toggleClass(element, ...classNames) {
                classNames.forEach((className) => {
                    element
                        .classList
                        .toggle(className);
                })
            }

toggleClass(myDiv, 'red', green', 'yellow');

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

(Photo by SLON V KASHE on Unsplash)

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.