getElementById returns null?
JavascriptGetelementbyidJavascript 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:
- Invalid HTML syntax (some tag is not closed or similar error)
- Duplicate IDs - there are two HTML DOM elements with the same ID
- 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
-
You have an invalid ID > ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html)
-
you used some id that you already used as
<meta>
name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/) -
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the
contentdocument
before looking for the element (resource: https://stackoverflow.com/questions/8710100/calling-a-specific-id-inside-a-frame/8710249#8710249) -
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case document.getElementById
should return at least the first element