Servant Servant - 1 month ago 21
Javascript Question

Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

I'm trying to use this solution -> http://stackoverflow.com/a/7410966/2007055

But why this code line with

.getElementsByTagName()
which is used by that solution, produced an error:

var tags = document.body.getElementsByTagName("*");
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null


Can somebody guess why it's producing the error and how can I fix it? (Thanks!)

Answer

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

Move the <script> from the <head> element to the <body> element (since you are trying to get all the elements in it, 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).