The simplest way to avoid an error Cannot read property 'addEventListener' of null
is to check whether the variable is null or not.
<button id="myButton">Click me</button>
var btn = document.getElementById('myButton');
if(btn){ //check if btn exists or not.
btn.addEventListener('click', myFunction);
}
function myFunction(){
console.log('Hello World');
}