Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById returns null? [closed]

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.

like image 974
Sheena Avatar asked Jan 05 '12 08:01

Sheena


People also ask

Why is my getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

How do I fix document getElementById is not a function?

To solve the "getElementById is not a function" error, make sure to spell the getElementById() method correctly, as it is case-sensitive, and only call the method on the document object, e.g. document. getElementById('btn') . Copied!

What does getElementById return if not found?

The getElementById() method returns null if the element does not exist.


2 Answers

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); 
like image 169
cameronroe Avatar answered Oct 02 '22 04:10

cameronroe


It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

Please, post your code.

like image 43
PanJanek Avatar answered Oct 02 '22 04:10

PanJanek