Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda