getElementById returns null?

Sheena picture Sheena · Jan 5, 2012 · Viewed 127.2k times · Source

document.getElementById('id of div that definately exists') returns null.

I originally loaded the javascript last in order to make sure I wouldn't need to worry about the onload event. I also tried using the onload event. It's very spooky. Any ideas or help would be greatly appreciated.

Answer

cameronroe picture cameronroe · Feb 19, 2013

Also be careful how you execute the js on the page. For example if you do something like this:

(function(window, document, undefined){

  var foo = document.getElementById("foo");

  console.log(foo);

})(window, document, undefined); 

This will return null because you'd be calling the document before it was loaded.

Better option..

(function(window, document, undefined){

// code that should be taken care of right away

window.onload = init;

  function init(){
    // the code to be called when the dom has loaded
    // #document has its nodes
  }

})(window, document, undefined);