Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

75
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda