Add or remove a class based on a condition

Viewed 1250

I am adding / removing a class from an element’s classList based on a variable’s truthiness. However, I’m doing it in what appears to be an obtuse way:

if (myConditionIsMet) {
  myEl.classList.add("myClass");
} else {
  myEl.classList.remove("myClass");
}

Is there a way in which I could make this more sexy and dynamically call the add / remove chained function for example with a conditional operator such as:

myEl.classList.{myConditionIsMet ? add('myClass') : remove('myClass')};

The above is pseudocode, of course, and I would like as plain JS as possible.

2 Answers

There’s a toggle method on .classList which takes a second argument (force). This boolean argument essentially takes a condition that adds the class if true, and removes the class if false.

myEl.classList.toggle("myClass", myConditionIsMet);

Your pseudocode js

myEl.classList.{myConditionIsMet ? add('myClass') : remove('myClass')};

can be translated to actual js

myEl.classList[myConditionIsMet ? 'add' : 'remove']('myClass');

which is not particularly readable, but does exactly what you described.

For readability, I would look at the toggle method.

Related