Home > Software design >  Javascript: Conditional not working. What am I doing wrong?
Javascript: Conditional not working. What am I doing wrong?

Time:07-17

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

  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");
  }
});

CodePudding user response:

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 >Test</div>

CodePudding user response:

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

  tekst.classList.toggle("red");

  • Related