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.