Uncaught TypeError: document.getElementById(...) is null
I have a single JavaScript file that is connected to multiple pages. The below snippet is a function that is used for a single page. The above error appears when the user navigates to one of the pages that does not use the below function, and it references the document.getElementById('button01').addEventListener('click', newThing);
line at the bottom. I've gathered that the error comes up due to the fact that button01
does not exist on these pages.
function newThing() {
const output = document.getElementsByTagName('output')[0];
if (!(document.forms.thingSelection2.type.value in options)) {
return false;
}
const list = options[document.forms.thingSelection2.type.value];
const method = document.forms.thingSelection1.mode.value + 'Item';
const item = list[method]();
output.innerHTML = item;
}
document.getElementById('button01').addEventListener('click', newThing);
Solution
My solution for this is simple; place the line in an if statement like so:
if(document.getElementById('button01')) {
document.getElementById('button01').addEventListener('click', newThing);
}
This removes the error from the pages that don't use it.
Questions
Does this open up the possibility for any buggy behavior that I don't know about? Is there a better way to achieve the same results?
HTML
I'm thankful for the feedback this post has received thus far. Since some of the answers contain recommendations based on assumptions of my HTML, I've decided to add the respective HTML in the below snippet. One thing to note is that I use two forms. This is required for the functionality of the code. I'm unaware of any unintended bugs this may cause. If it does, please let me know below.
<div><output></output></div>
<div><button id="button01">New Thing</button></div>
<div>
<form name="thingSelection1">
<input type="radio" name="mode" value="random" id="mode1"> Random
<br/><input type="radio" name="mode" value="forward" id="mode2"> Old - New
<br/><input type="radio" name="mode" value="reverse" id="mode3"> New - Old
</form>
</div>
<div>
<form name="thingSelection2">
Doodle <input type="radio" name="type" value="doodle" id="doodleCheck"><br/>
Video <input type="radio" name="type" value="video" id="videoCheck"><br/>
Audio <input type="radio" name="type" value="audio" id="audioCheck"><br/>
Photo <input type="radio" name="type" value="photo" id="photoCheck"><br/>
Text <input type="radio" name="type" value="text" id="textCheck">
</form>
</div>
Furthermore, I'd like to point out that the original snippet is only part of my full JavaScript. Based on the information provided by this post, I've concluded that adding the remaining JavaScript, while possibly beneficial and relevant to some of the answers below, could possibly be out of the scope of the original topic of this post. Please note your thoughts on this in the comments below.