Hi community, I am actually new to web development and coding, recently I try to create a website using html, css and javascript and I have multiple html files but only one css and one javascript file.
Here is my problem, in my javascript file I am getting a DOM element from the second html page and adding a class to it but when I visit my other pages the console shows an error( Uncaught TypeError: Cannot read property ‘classList’ of null ), the error only disappear when I visit the second html page which is where I grab the DOM from.
index.html
<body>
<div class="index">
<h1>Index</h1>
</div>
<script src="./script.js"></script>
</body>
about.html
<body>
<div class="about">
<h1>About</h1>
</div>
<script src="./script.js"></script>
</body>
contact.html
<body>
<div class="contact">
<h1>Contact</h1>
</div>
<script src="./script.js"></script>
</body>
script.js
const aboutContainer = document.querySelector('.about');
aboutContainer.classList.add('show');
Am I missing something out in my code or I can’t just use one script file for all my html files? do I need to give each html their own javascript file?
something like:
index.html --> index.js
about.html --> about.js
contact.html --> contact.js
But what about if I have 10 html files do I also need to create 10 javascript files?
is this the correct way, like creating 5 html pages and also have 5 javascript files?
Thanks