In the index.html page I have the following code
<body>
<h1>First page</h1>
<button id="submitBtn">Submit</button>
<script src="script.js"></script>
</body>
The JS is a simple script that redirects the page to another page – second.html
document.getElementById('submitBtn').addEventListener('click', function(e) {
e.preventDefault();
window.location.href = 'another_file.html';
})
Once the second page is loaded, the console gives – TypeError: Cannot read properties of null (reading ‘addEventListener’). This is understandable as the next page doesn’t have the submitBtn.
How can I avoid this error?
Thanks
>Solution :
You can check if it exists before attaching events to it.
var elem = document.getElementById('submitBtn');
elem && elem.addEventListener('click', function(e) {
e.preventDefault();
window.location.href = 'another_file.html';
})