Servant Servant - 1 year ago 137
Javascript Question

Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

I'm trying to use this solution ->

But why this code line with

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 Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download