How to fix “Cannot read property ‘addEventListener’ of null” error [duplicate]

You are loading the Javascript file in the <head>, before the body of your HTML Is loaded. Therefore your line

const guessSubmit = document.querySelector('.guessSubmit');

Has nothing to look up – your button with class guessSubmit doesn’t exist yet. And since guessSubmit is null, it does not contain any properties, hence the error.

The easiest solution is to put your <script> tag at the bottom of your HTML body rather than the head. This way it will load your Javascript after the DOM is completely loaded.

Alternative ways include adding event listeners to run your script after the DOM is loaded, such as DOMContentLoaded. See more here: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded.

Leave a Comment