Thread: Div object null
View Single Post
Old 12-08-2012, 10:44 PM   PM User | #1
CMaso
New Coder

 
Join Date: Dec 2009
Posts: 15
Thanks: 1
Thanked 0 Times in 0 Posts
CMaso is an unknown quantity at this point
Div object null

I'm having a problem with a simple script. I declare a function at the top of my page that will populate a div down the page. Immediately below is the div tag, and then below the div tag I call the function. I figure (wrongly, it seems) that having the div before the function call ensures that the function won't run before the div exists.

Code:
<script>
     function populateDiv(id) {
           var objDiv = document.getElementById(id);
           objDiv.innerHTML = "This is text for the div";
     }
</script>

<div id="myDiv" />

<script>
     populateDiv("myDiv");
</script>
The code above generates a js error, saying that "objDiv" is null. So I added an attachEvent to call the function onLoad, instead:

Code:
<script>
     function populateDiv(id) {
           var objDiv = document.getElementById(id);
           objDiv.innerHTML = "This is text for the div";
     }

     window.attachEvent('onLoad', populateDiv('myDiv'))); 
</script>

<div id="myDiv" />
But this still generates the same error; objDiv is null.

Adding to my confusion, it works if I trigger the function call with a button instead:

Code:
<script>
     function populateDiv(id) {
           var objDiv = document.getElementById(id);
           objDiv.innerHTML = "This is text for the div";
     }
</script>

<input type="button" value="Click here to populate div" onClick="populateDiv('myDiv');">

<div id="myDiv" />
I don't want to have to trigger the function with any human action; I want it to run automatically when the page loads. I figure it's a timing thing; I could put in a time delay of some kind, but that seems like a hack. What can I do, and why is the code breaking in the first two instances?

Thanks,
CM
CMaso is offline   Reply With Quote