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

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

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 Relatório

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 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