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

249
Vistas
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 Respuestas
Responde la pregunta

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