Categories
JavaScript Answers

How to fix the “Uncaught TypeError: Cannot read property ‘getElementsByTagName’ of null” error with JavaScript?

Spread the love

Sometimes, we want to fix the "Uncaught TypeError: Cannot read property ‘getElementsByTagName’ of null" error with JavaScript.

In this article, we’ll look at how to fix the "Uncaught TypeError: Cannot read property ‘getElementsByTagName’ of null" error with JavaScript.

How to fix the "Uncaught TypeError: Cannot read property ‘getElementsByTagName’ of null" error with JavaScript?

To fix the "Uncaught TypeError: Cannot read property ‘getElementsByTagName’ of null" error with JavaScript, we should move script tags into the body element to make sure it’s run when the body element is loaded.

For instance, we write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Page</title>
  </head>
  <body>
    <div></div>
    <div></div>
    <script>
      console.log(document.body.getElementsByTagName("div"));
    </script>
  </body>
</html>

to call document.body.getElementsByTagName with 'div' to select the divs after they’re loaded.

We make sure they’re loaded before running the script by putting the script tag below the divs within body.

Conclusion

To fix the "Uncaught TypeError: Cannot read property ‘getElementsByTagName’ of null" error with JavaScript, we should move script tags into the body element to make sure it’s run when the body element is loaded.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *