getElementById returns null?

JavascriptGetelementbyid

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

There could be many reason why document.getElementById doesn't work

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSheenaView Question on Stackoverflow
Solution 1 - JavascriptcameronroeView Answer on Stackoverflow
Solution 2 - JavascriptPanJanekView Answer on Stackoverflow
Solution 3 - JavascriptFabrizio CalderanView Answer on Stackoverflow