Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

I'm trying to select elements with .getElementsByTagName().

var tags = document.body.getElementsByTagName("*");

Current attempt using lessons learned from an existing answer https://stackoverflow.com/questions/7410949/javascript-document-getelementsbyclassname-compatibility-with-ie/7410966#7410966

But my attempt failed and I have this error:

Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

Why is it producing this error and how can I fix it?

like image 910
5ervant - techintel.github.io Avatar asked Apr 24 '14 08:04

5ervant - techintel.github.io


1 Answers

Move the <script> from the <head> element to the <body> element.



document.body won't get a value assigned to it until the body element has been created.

Since you are trying to get all the elements in the <body>, you'd want to be at the end of the body element. Or put it in a function and call it from an event that fires after the body has been created (such as the window load event). To read more about that try, https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event.

like image 147
Quentin Avatar answered Sep 29 '22 09:09

Quentin