...

View Full Version : Why is fooDiv null?



GummyBear
09-21-2005, 09:46 PM
Hi there, I'm having a problem with a null reference that I can't seem to figure out. I'd like to dynamically work with the fooDiv object referenced from the document.writes as you can see from the following snippet.

<html>
<head>
<script language="javascript" type="text/javascript">
<!--
document.write('<div id="foo"><\/div>');
document.write('<script language="javascript" type="text/javascript">');
document.write('var fooDiv = document.getElementById("foo");');
//do sweet stuff with fooDiv
document.write('<\/script>');
</head>
The problem is that fooDiv is null when i try to access it.
Can someone help me out? I'm loosing my hair on this one :<

martin_narg
09-21-2005, 09:56 PM
Wait for the page to be loaded before trying to access and manipulate it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = function() {
var fooDiv = document.getElementById("foo");
alert(fooDiv);
}
</script>
</head>

<body>
<script type="text/javascript">
document.write('<div id="foo">&nbsp;</div>');
</script>
</body>
</html>
Hope this helps.

m_n

GummyBear
09-22-2005, 10:20 AM
Thanks for your response martin, but that's not really what I'm lookin for unfortunately.
What I was really trying to do is interact with the dynamically created DIV while the page is still rendering, without having to wait for the onload event to fire.

I noticed that if I use the following code the DIV is accessible:

<html>
<head>
<script language="javascript">
<!--
document.write('<div id="foo"><\/div>');

-->
</script>
//some other tag
<script language="javascript">
<!--
document.write('<script language="javascript" type="text/javascript">');
document.write('var fooDiv = document.getElementById("foo");');
//do sweet stuff with fooDiv
document.write('<\/script>');
-->
</script>
</head>
Notice that between the two <script> tags there is some other tag...for example a css block or a meta tag. Strangely this works even if the page hasn't finished loading. Probably the scripting engine flushes the code to the browser's rendering engine at the end of the first <script> tag, so that when the second block of JS code runs the browser already has a reference to the objects.

The problem is that I'm loading the script from a src attribute from an external .js file, and I have to keep everything contained within the single .js file. :(



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum