Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!