tags:

views:

422

answers:

3

Hi,

i want someone to include a JS file of me which does something neat. I thought i put it up just like Google: you put a script tag in your source and the google js takes care of everything. in my php file is this:

echo '<script type="text/javascript"
src="http://www.site.com/gadget.js"&gt;
</script>';

i that gadget.js, i write a span:

document.write('<span id="GadgetPicture>');
document.write('</span>');
window.setTimeout('refreshImage();', 2000);

in the refreshImage function, i want to reference my span:

document.getElementById("GadgetPicture");

But it gives me null... Does anybody know why?

also, document.getElementById("body") also give null.

Michel

A: 

You can append a span element in your body without using document.write method. document.write is not a proper way of inserting elements to the DOM.

Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page.

You can use the

appendChild

method for doing this.

rahul
+6  A: 

You're missing a quote:

document.write('<span id="GadgetPicture">')

It's generally better to use DOM methods (createElement, appendChild) than document.write, but it should still work.

Greg
+1  A: 

For one your missing the quote in the <span> like everyone has said, and you should not be using the document.write to create new elements on the page as Greg said use createElement and appendElement like;

var span = document.createElement('span');
span.id = 'GadgetPicture';

document.appendChild(span);

You could also use jQuery and the HTML helper http://docs.jquery.com/Attributes/html#val

Also in your setTimeout method you should use it like;

setTimeout(function() { refreshImage(); }, 2000);

or

setTimeout(refreshImage, 2000);

Declaring a string will cause Javascript to use eval on the contents.

You can get the body of the document with getElementsByTagName as the body tag is not something that usually has an ID.

document.getElementsByTagName("body")[0]

You can safely assume that the first found element will be the body your after, as a page with multiple would be invalid HTML.

sixones
thanks very much, the quote did the trick (that realy annoys me though, tried 101 things, but forgot to look at the quote...). ALtered the function name to the function itself, and gonna try the createelement code.
Michel