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

248
Visualizações
Why does the button not change color with this code?

I am new to web dev and am just doing some exercises related to HTML, CSS, and Javascript. I have created a button in my html file and want to change the color of the button if it is clicked on.

This is my HTML code:

<button id="box" style="padding: 20px; background-color: black;"></button>

This is my Javascript code:

document.addEventListener('click', event => {
    if (event.target.id === 'box') {
        document.style.backgroundColor="red";
    }
})

Not quite sure why it is not working.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

document doesn't have a style property (at least, not by default in spec-compliant browsers). Your developer console should inform you of this with a message akin to:

Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor')

Instead, be a bit more specific as to which element's background color you'd like to change. In the example below, I've modified your code to target document.body, which has a style element:

document.addEventListener('click', event => {
    if (event.target.id === 'box') {
        document.body.style.backgroundColor="red";
    }
})
<button id="box" style="padding: 20px; background-color: black;"></button>

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