Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda