4

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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
physicsboy
  • 5,656
  • 17
  • 70
  • 119
  • I knew of toggle, but I didn't know it also took a Boolean! Looks like this might to the trick :-) – physicsboy Oct 20 '21 at 07:19
  • Does this answer your question? [How to set a Javascript object values dynamically?](https://stackoverflow.com/questions/6439915/how-to-set-a-javascript-object-values-dynamically) – Thomas Sablik Oct 20 '21 at 07:25
  • The same thing with jQuery: [Neater way of checking adding/removing a CSS class using 'hasClass' in jQuery?](/q/8619466/4642212). – Sebastian Simon Oct 20 '21 at 07:26
  • [How do I call a dynamically-named method in Javascript?](https://stackoverflow.com/questions/969743/how-do-i-call-a-dynamically-named-method-in-javascript) – Thomas Sablik Oct 20 '21 at 07:29

2 Answers2

9

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);
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
6

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.

edo.n
  • 2,184
  • 12
  • 12