Code isn't reading addEventListener()

I’ve been stuck on this for a while now, and I don’t understand what’s wrong. I’m making a guess-my-number type of game, but the computer isn’t finding my element (<button>) that has an id of clickButton. Any help?:

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="script.js"></script>
    <input type="number" id="your-guess" /><br /><br /><br />
    <button id="clickButton" class="basic-text">Click me to check</button
    ><br /><br /><br />
  </body>
</html>

JS:

function checkInputFunch() {
  const userInputNum = Number(document.querySelector("#your-guess").value);

  if (!userInputNum) {
    displayInputStatusMessage("Please insert a number");
  } else if (userInputNum > correctNum) {
    displayInputStatusMessage("Too high...");
  } else if (userInputNum < correctNum) {
    displayInputStatusMessage("Too low...");
  }
}

document
  .querySelector("#clickButton") // this is 15:3, where the error is 
  .addEventListener("click", checkInputFunc());

Error Message:
TypeError: Cannot read property 'addEventListener' of null at /script.js:15:3

JS selecting that button is executed before whole page is loaded, and at that time button actually doesn’t exist. What you are looking for is a way to make js execute after the whole page is loaded.

How can I make it execute before? My script tag is before the button and is in the HTML head.

Move the script tag to the very end of the body.

Alternatively, if you want your script to stay inside the <head>, put your code into a DOMContentLoaded event listener callback:

document.addEventListener('DOMContentLoaded', () => {

    // your code goes here

}
1 Like