If we have two elements in two different pages say 'element1' in page-1 and 'element2' in page-2. And we have a single javascript linking both the pages say 'main.js' like this
HTML (PAGE 1)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
</head>
<body>
<h1 class="elementOne">THIS IS ELEMENT ONE</h1>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
HTML (PAGE 2)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
</head>
<body>
<h1 class="elementTwo">THIS IS ELEMENT TWO</h1>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
MAIN.JS (JAVASCRIPT FILE LINKING BOTH PAGES)
let elementOne = document.querySelector(".elementOne");
let elementTwo = document.querySelector(".elementTwo");
elementOne.addEventListener("click",(e)=>{
console.log("element1");
})
elementTwo.addEventListener("click",(e)=>{
console.log("element2");
})
If the current page is 'page1' we get a error
Cannot read property 'addEventListener' of null
Because
document.querySelector(".elementTwo);
returns null
,
Since element with the class 'elementTwo' does not exist in PAGE1
I found a solution for this here
In the link provided above, they are checking for null
like this
if(elementOne){
elementOne.addEventListener("click",(e)=>{
console.log("element1");
})
}
if(elementTwo){
elementTwo.addEventListener("click",(e)=>{
console.log("element2");
})
}
Is there a better way to do this?. I also observed that this problem does not occur if we use jQuery.
Thanks for any help :)