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

302
Vistas
How can I rewrite this code using a ternary operator?

The following is a code I have written to change a grid color to indigo upon clicking it, then removing the color upon the second click. However, I do not know how to rewrite the if-else statement using a ternary operator.

const grid1=document.querySelector(".cell01")
grid1.addEventListener("click", (e)=>{
    console.log(e);
    if (grid1.style.backgroundColor) {
      grid1.style.backgroundColor = "";
      } else {
        grid1.style.backgroundColor = "indigo";
      }
})

Thank you for your help in advance (:

Update Thanks for the answers! But now I have one more inquiry -- I wanted to try different ways of rewriting the same code, and came up with this:
grid1.style.backgroundColor=(grid1.style.backgroundColor!=true) ? "indigo" : "";

It did exactly what I wanted with the expression (grid1.style.backgroundColor==false), but not in the case of the former. Is there a reason why?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Straightforward translation into a ternary:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo"; 
about 4 years ago · Juan Pablo Isaza Denunciar

0

grid1.style.backgroundColor = grid1.style.backgroundColor ? '' : 'indigo'
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try this:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";

Checkout below reference to learn more about ternary operator https://www.freecodecamp.org/news/ternary-operator-javascript-if-statement-tutorial/

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