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
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?