Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

275
Views
Add or remove a class based on a condition

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!