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

76
Views
Check class existence after clicking an element

I'm trying to brush up my javascript and have a simple setup of html, CSS and JS connected.

The console.log prints out Clicked so I know it's working, but my code is wrong and I can't see it. The element is not checking for the existing class 'red'.

I'd like to check if the class red is there, and if it is then remove it and if its not, then add the class.

Can any of you point me in a direction?

TIA

tekst.addEventListener("click", () => {
  console.log("Clicked");
  tekst.classList.add("red");

  if (tekst.classList.contains("")) {
    tekst.classList.add("red");
  } else if (tekst.classList.contains("red")) {
    tekst.classList.remove("red");
  }
});
about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Your code works. But you're adding red and then immediately removing it so you won't see a change.

The alternative to the conditional is to just toggle the class instead. (I've added a timeout so you can see this working).

const tekst = document.querySelector('.tekst');

// Comment this line out to see the reverse effect
tekst.classList.add("red");
setTimeout(() => tekst.classList.toggle('red'), 2000);
.red { color: red; }
<div class="tekst">Test</div>

about 4 years ago · Santiago Gelvez Report

0

In my point of view, you just need to use toggle method like so:

  tekst.classList.toggle("red");

about 4 years ago · Santiago Gelvez 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!