|
|||||||
New to SitePoint Forums? Register here for free!
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
SitePoint Addict
![]() ![]() ![]() Join Date: Jun 2007
Posts: 266
|
getElementById returns null
Hi,
Suppose I have the following inside a function: JavaScript Code:
The above works. However, when I define it like the following it says display_content is null on firefox error console. JavaScript Code:
Any suggestions? when I replace display_content with document.getElementById('display_content'), it works. |
|
|
|
|
|
#2 |
|
padawan
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jul 2006
Location: Victoria, Australia
Posts: 3,029
|
Hi, make sure the html has finished loading before you run the script.
Code:
window.onload = function() {
var display_content = document.getElementById('display_content');
}
function render() {
display_content.innerHTML = "hello";
}
|
|
|
|
|
|
#3 |
|
SitePoint Addict
![]() ![]() ![]() Join Date: Jun 2007
Posts: 266
|
It still gives the same error, but if I define the function within the onload then it works
Code:
window.onload = function()
{
var display_content = document.getElementById('display_content');
function render()
{
display_content.innerHTML = "hello";
}
}
|
|
|
|
|
|
#4 |
|
Programming Since 1978
![]() ![]() ![]() ![]() Join Date: Sep 2005
Location: Sydney, NSW, Australia
Posts: 10,814
|
The display_content in the window.onload anonymous is defined local to that function. It no longer exists by the time the render function tries to access a global variable by the same name.
|
|
|
|
|
|
#5 |
|
padawan
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jul 2006
Location: Victoria, Australia
Posts: 3,029
|
You should try to avoid using global variables too so the following is probably the best.
If functions need references to other objects just pass them as parameters. javascript Code:
|
|
|
|
|
|
#6 |
|
SitePoint Addict
![]() ![]() ![]() Join Date: Jun 2007
Posts: 266
|
defining the objects locally does the trick, thanks.
![]() |
|
|
|
![]() |
| Bookmarks |
«
Previous Thread
|
Next Thread
»
| Thread Tools | |
| Display Modes | |
|
|
|
All times are GMT -7. The time now is 21:05.















Linear Mode
