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

72
Views
Comprobar la existencia de clases después de hacer clic en un elemento

Estoy tratando de refrescar mi javascript y tener una configuración simple de html, CSS y JS conectados.

El archivo console.log imprime Clicked , así que sé que funciona, pero mi código es incorrecto y no puedo verlo. El elemento no busca la clase existente 'red'.

Me gustaría verificar si la clase red está allí, y si lo está, eliminarla y, si no, agregar la clase.

¿Alguno de ustedes puede señalarme una dirección?

AIT

 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

Tu código funciona. Pero está agregando rojo y luego lo elimina de inmediato para que no vea un cambio.

La alternativa al condicional es simplemente toggle la clase. (He agregado un tiempo de espera para que pueda ver cómo funciona).

 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

En mi punto de vista, solo necesita usar el método de alternar así:

 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!