Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent looking for DOM elements after window.location.href (redirection)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading