Skip to content Skip to sidebar Skip to footer

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 http

Solution 1:

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.


Solution 2:

Function examples:

Example with both methods:

function init() {
  alert("hello javascript");
};

window.addEventListener("load",init,false);

$(document).ready(function () {
  alert("hello jQuery");
});

http://jsfiddle.net/Ln5zu4Lt/

Be careful, the JavaScript example above waits for page load (images, iframes, etc.). This takes more time than jQuery's ready.


Post a Comment for "Uncaught TypeError: Cannot Read Property 'getElementsByTagName' Of Null"