0
Here is a simple example to demonstrate the doubt. There are two pages and a script. I know it works by importing the script on both pages, but when I use the eventListener
, it shows the error saying that it did not find the target element of the page that was not loaded. Although in this simplest example works, the error message keeps appearing on the console, and in more complex examples the event stops working.
Error message:
"Uncaught Typeerror: Cannot read Property 'addeventlistener' of null"
Page 1:
<body>
<button id="botao1">botão 1</button>
<script src="script.js"></script>
Page 2:
<body>
<button id="botao2">botão 2</button>
<script src="script.js"></script>
JS:
let botao1 = document.getElementById("botao1");
let botao2 = document.getElementById("botao2");
botao1.addEventListener("click", () => {
alert("botao 1");
});
botao2.addEventListener("click", () => {
alert("botao 2");
});
How about making a simple
if
? Or separate scripts? Or put JS directly in a tagscript
?– Cmte Cardeal
So this was an example, but the project I’m doing has an 87-line script, it wouldn’t be good practice to put it in every html. The ideal option would really be to separate the scripts, but I would like to know if it is possible to resolve this issue the way I left it there. How "if" would solve this question?
– Glebson Santos
And validate that the button exists? if(typeof(boot 1) != 'Undefined' && boot 1 != null){ Alert('Button exists!'); botao1.addeventlistener("click", () => { Alert("boot 1"); }); } Else{ Alert('Button does not exist!'); }
– António Campos
I get it, thank you :)
– Glebson Santos
But the code for both buttons is the same ?
– Isac