javascript – getElementById returns null?

javascript – getElementById returns null?

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

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.

javascript – getElementById returns null?

There could be many reason why document.getElementById doesnt 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: 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/)

  • youre 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: Calling a specific id inside a frame)

  • youre simply looking to an element when the node is not effectively loaded in the DOM, or maybe its a simple misspelling

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

Leave a Reply

Your email address will not be published.