So how do you make sure that this doesn't happen to you?
You can check if the element exists by checking the type and if it's null first.
var element = document.getElementById('the-elements-id');
if (typeof(element) != 'undefined' && element != null) {
console.log('The element exists!');
}
This code will look for an element called "the-elements-id". And then it checks if that element is not undefined and is not null. This way, you can be sure that it's safe to execute code on the element variable.