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

Time:09-30

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

CodePudding user response:

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

As for your design decision the way I would structure it indeed use script.js for all the functions and the only difference is between the pages which own has a minimal <script> tag to initialize and insatiate its own stuff.

So for this instance, while both share the same script.js, only index.html page would include this snippet of code inside of it. and second.html should not bother at all with checking for that element.

CodePudding user response:

Do you have this in the "another_file.html"?

<script src="script.js"></script>

Because if you do, this is causing the issue.

  • Related