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

144
Visualizações
One common script.js file in two html page causing errors

I am basically a beginner in programming world. So currently facing a problem that I don't understand in which way I should search this solution. So I am here for help. Hope someone can help me. I really need this solution.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Game1</title>
</head>

<body>
    <p id="p1">Lorem ipsum dolor sit amet.</p>

    <script src="script.js"></script>
</body>

</html>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Game2</title>
</head>

<body>
    <p id="p2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, quis!</p>

    <script src="script.js"></script>
</body>

</html>

(function() {
    const p1 = document.getElementById('p1');
    const textChange1 = () => {
        p1.innerHTML = 'textChange 1';
    }
    p1.addEventListener('click', textChange1);
})();


(function() {
    const p2 = document.getElementById('p2');
    const textChange2 = () => {
        p2.innerHTML = 'textChange 2';
    }
    p2.addEventListener('click', textChange2);
})();

So I want to run this script.js file in both Game1.html and Game2.html.

But it causing one error ![Text]https://i.ibb.co/BPVBv4N/html.jpg in Game1.html

script.js:15 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at script.js:15:8
at script.js:16:3

in Game2.html

script.js:6 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at script.js:6:8
at script.js:7:3

I want to use one script file. When game1.html access it I want game1.html to access only the code including id='p1'; and when its game2.html ,I want it to access only the part of js that include id='p2'; how can I achieve this, that the html use only the part of js that is needed not the others.

just like we use one css in multiple html .

note- I want only to use one js file no other sub-js file. Thanks.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Check the element prior to executing, wrap your functions in something like this:

if (document.getElementById('p1') !== null){
 //p1 exists, continue
}

if (document.getElementById('p2') !== null){
 //p2 exists, continue
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Since the element with id p2 doesn't exist in your first HTML file, it returns undefined. That's why calling p2.addEventListener wont work, because addEventListener is not on undefined.

To fix this you could add a check for if the element existed and only continue if it does.

(function() {
    const p1 = document.getElementById('p1');
    if(!p1) return; // Just replace it with p2 for the other part
    const textChange1 = () => {
        p1.innerHTML = 'textChange 1';
    }
    p1.addEventListener('click', textChange1);
})();
about 4 years ago · Juan Pablo Isaza Relatório

0

To use the same script.js for the 2 pages you need to check if the element you are selecting exists on that page before adding addEventListener like the example below.

(function() {
    const p1 = document.getElementById('p1');
    if(p1){
        const textChange1 = () => {
            p1.innerHTML = 'textChange 1';
        }
        p1.addEventListener('click', textChange1);
    }
})();


(function() {
    const p2 = document.getElementById('p2');
    if(p2){
        const textChange2 = () => {
            p2.innerHTML = 'textChange 2';
        }
        p2.addEventListener('click', textChange2);
    }
})();
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