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