Cannot read property 'addEventListener'

I have some javascript code associate with an HTML file. If I run this HTML file and open console there is an error look like,

Uncaught TypeError: Cannot read property ‘addEventListener’ of null
at 16.3.js:3

11

My HTML code:

<!DOCTYPE html>
<html>
<head>
	<title>Color Exercise</title>
	<script type="text/javascript" src="16.3.js"></script>
</head>
<body>
	<button>Change color</button>
</body>
</html>

My javascript code:

var button = document.querySelector('button');

button.addEventListener("click", function(){
	alert("Clicked!");
});

But, if I run this javascript code manually in the console then it works fine. What’s going on here, why I am getting this error?

Your script is running before the HTML is constructed.
Either add a defer attribute or move the script to just before the closing body tag

1 Like

Thank you! It’s working now :relaxed:

<!DOCTYPE html>
<html>
<head>
	<title>Color Exercise</title>
</head>
<body>
	<button>Change color</button>
	<script type="text/javascript" src="16.3.js"></script>
</body>
</html>