'Element does not exists on specific page
I've created a website that has index.html and quiz.html, one style.CSS and one app.JavaScript.
I have added some functions in the JS that refer to both pages. Lets say: Page 1 index.html: the app.js has an event listener to show a box on click. That box then has a button to move to quiz.html (all works fine). Page 2 quiz.html: on JavaScript I have functions to make the quiz run. The problem is that the code breaks before it gets to the functions for the quiz, with a line referring to the first page.
Error: app.js:14 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at app.js:14:35
Line 14 is document.getElementById('btnPlay').addEventListener('click', openBox), that refers to an element within index.html, not the page I am now quiz.html.
I understand why, because on this current page we don't have a reference to it. But I have read in many places that is usually better to use one app.js file and not one per html page. How do we make this work? Any suggestions?
Solution 1:[1]
On some page B you don't have that #btnPlay Element therefore document.getElementById('btnPlay') equals undefined. And you cannot assign an event listner to it: undefined.addEventListener.
To make sure that element exists — before moving forward
use Optional Chaining ?..
document.getElementById('btnPlay')?.addEventListener('click', openBox)
otherwise on page B the "#btnPlay" is not found and your JavaScript will break.
Another "old" way to tackle that issue would've been using a statement:
const EL_btnPlay = document.querySelector("#btnPlay");
if (EL_btnPlay) EL_btnPlay.addEventListener("click", openBox);
where the aforementioned is just a shorthand to do the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
