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

115
Vistas
Assign document.body.style.backgroundColor to a variable

I'm making a simple color changer. And I assigned document.body.style.backgroundColor to valuable backgroundColor. When I console.log(backgroundColor) , I can see it's working but background color doesn't change. So I just deleted the variable backgroundColor and put document.body.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]; and then it works! But I can't understand why it doesn't work when I assigned document.body.style.backgroundColor to a variable as below code.

const btn = document.querySelector('.btn');
const color = document.querySelector('.color');
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];

btn.addEventListener('click', function() {
    
    let backgroundColor =  document.body.style.backgroundColor ;
    backgroundColor  = colors[Math.floor(Math.random() * colors.length)];
  
console.log(backgroundColor)

})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

By doing that you are just copying (saving) the literal value of the document.body.style.backgroundColor, not a thing to point at that. so assigning a new value to the variable doesn't affect the document.body.style.backgroundColor.

You are just changing the value again:

backgroundColor  = colors[Math.floor(Math.random() * colors.length)];
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