Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

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

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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos