DEV Community

Cover image for Javascript – Swap classes of an HTML element
Latz
Latz

Posted on

2

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 naive solution to my problem:

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

const myDiv = document.getElementById('myDiv'); 
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.

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay