-1

I'm new at programming and I am trying different things and today I tried this:

HTML:

<button id="button">Blue button</button>

JavaScript:

let button = document.getElementById("button");

button.onclick = function() {
  element.style.backgroundColor = "red";
  element.style.color = "white";
  element.innerHTML = "Red Button";
}

And the console says: cannot set property 'onclick' of null

Ivar
  • 6,138
  • 12
  • 49
  • 61
John
  • 25
  • 1
  • 3
  • The element that you try to access in your function is not defined anywhere, you need to either use `button.style.backgroundColor ...` instead of `element.style.backgroundColor` or you need to access the clicked element in the on click function. Passing in function a variable to capture the event `= function(e)` and then access the element `e.target.style.backgroundColor` – RDU Jun 15 '21 at 13:51

1 Answers1

0

The element probably hasn't been loaded when you tried selecting it. Add an event listener for DOMContentLoaded:

document.addEventListener("DOMContentLoaded", function() {
  let button = document.getElementById("button");

  button.onclick = function() {
    button.style.backgroundColor = "red";
    button.style.color = "white";
    button.innerHTML = "Red Button";
  }
})
<button id="button">Blue button</button>
Spectric
  • 30,714
  • 6
  • 20
  • 43