Wednesday, December 7, 2011

Document.getElementById return null

The problem
Document.getElementById() - The most useful and common use features while developing in javascript. Some how this function call will failed unexpected without any javascript error. The most common error for this function is returning a NULL even we can 100% confirm the element with correct ID is there!

The catch
Come on, this is not a browser issue nor javascript issue. There are few possible that trigger this issue. Listed below is what I faced before, if you have more please share by replying a comment. TQ.

1.  ID had been used more than once in a HTML page
Check is the ID the element has been used more than once in a HTML. The most easier way to debug is right click on the web browser and click VIEW SOURCE (CTRL U). From there use the find tool to search for the ID that document.getElementById() cannot found.

2. Nested <FORM> 
document.getElementById() return null while trying to get a <FORM> element? Make sure that the <FORM> element you try to get is not under another <FORM> element! This error is usually happen while using PHP framework or template based framework.

Try to move the inner <FORM> element out from the parent form. For Symfony PHP framework, sometime this is hard to archive because we are good programmer that make our code modular enough to screw ourselves up :P . In this case, you can use the SLOT concept in Symfony to solve this problem.

You know something is not listed here, please reply a comment to share. TQ.

No comments:

Post a Comment