Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda