1

I'm trying to make a button that prints the string "Button clicked" on the console when clicked, but I keep getting the error Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at course.js:70.

This is the code for the HTML button:

<button id="go-button">Go</button>
<br>
Click that button

And this the Javascript for it:

function buttonClicked(){
console.log("Button clicked");
}

var btn = document.getElementById("go-button");
btn.addEventListener("click", buttonClicked, true);

I'm following a video course from 2017 and copied the exact code the instructor wrote, but his runs as intended. I thought that maybe it was an outdated method and that was causing the problem, but then looked it up and about three websites showed similar examples. Honestly, I got confused.

Luis M.
  • 597
  • 2
  • 5
  • 13
  • 3
    Maybe your javascript code is getting executed even before your button was loaded into the DOM. Could you share a live example with plunk/codepen? where are you referencing your js file in your HTML? – Paritosh Nov 23 '21 at 05:21
  • FYI your code does work so work through the solution that Paritosh has provided. – Andy Nov 23 '21 at 05:40

2 Answers2

6

Your code seems to be executed even before the DOM getting loaded into the browser.
Put it under window.onload. That way it would be able to find go-button and then would be able to add event listener to it.

function buttonClicked(){
    console.log("Button clicked");
}

window.onload=function(){
  var btn = document.getElementById("go-button");
  btn.addEventListener("click", buttonClicked, true);
}

Reference: Cannot read property 'addEventListener' of null

OR

Put your script import at the end of your HTML's body

<html>
    <body>
        .........
        <script src="main.js"></script>
    </body>
</html>

Reference: Another answer to the above question

Paritosh
  • 11,144
  • 5
  • 56
  • 74
  • Putting my script import at the end of my HTML's body solved it. Thanks a lot, Paritosh. You sure live up to the name, haha. Have a nice day. – Luis M. Nov 23 '21 at 11:54
  • please why did my own work only for the first time when the page loads, if I refresh the page the error surfaces again – Arinzehills May 25 '22 at 12:40
0

Add the defer attribute to the script element that links your js code in your html. This would prevent your code from executing before the DOM gets loaded into the browser

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – jasie Sep 29 '22 at 10:42