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

139
Vistas
Setting style.background as a var doesn't work

I modified this working Javascript code by setting style.background as var "x" and it doesn't toggle anymore. Where is the problem?

<script>
var myVar = setInterval(setColor, 300);
 
function setColor() {
/* This commented-out code works.
  var x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
  */
  var x = document.body.style.backgroundColor;  // not working
  x = x == "yellow" ? "pink" : "yellow";
}
</script>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your assigning value to variable "x", not document.body.style.backgroundColor, don't store it in a variable.

<script>
var myVar = setInterval(setColor, 300);
 
function setColor() {
  var x = document.body.style.backgroundColor; 
  document.body.style.backgroundColor = x == "yellow" ? "pink" : "yellow";
}
</script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

That's because in the original code:

function setColor() {
  var x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

x is a reference of document.body, nevertheless, in your code, when you do:

x = x == "yellow" ? "pink" : "yellow";

x is not equal to a reference of document.body anymore, now it is a string, either pink or yellow. So, x will not change the html because it is only a string variable.

If you want the code to work, you need to add this code behind x declaration.

document.body.style.backgroundColor = x
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