Y
yawnmoth
I'm having some difficulty with adding elements to a webpage via the
DOM. The following works:
main.htm:
<script>
js = document.createElement('script');
js.src='test.js';
document.getElementsByTagName('head')[0].appendChild(js);
</script>
test.js:
alert('hello, world!');
But this doesn't:
main.htm:
<script>
img = document.createElement('img');
img.src='image.jpg';
document.getElementsByTagName('body')[0].appendChild(img);
</script>
This got me thinking that maybe webbrowsers don't auto-create bodies
for websites whereas they do heads. To test this, I tried to write a
script that'd list all that was created by the browser:
main.htm:
<script>
nodes = document.childNodes;
for (i=0;i<nodes.length;i++)
{
document.write(nodes.nodeTypedValue+'<br />');
}
</script>
Unfortunately, this script just prints out undefined. I tried switched
nodeTypedValue out with node TypeString to no avail.
I then decided to try and modify the second main.htm. I tried making
it look for elements with the tag name of 'head' instead of 'body', but
that didn't help. I tried adding a newly creating body element (whose
bgcolor was black) but that didn't work, either. I even tried adding a
title tag via appendChild to 'head' (whose text was specified by a
createTextNode) but that didn't do anything, either.
So... why can I add javascript files via the method in the first
main.htm when I can't add anything else?
Also, why doesn't the second main.htm work?
DOM. The following works:
main.htm:
<script>
js = document.createElement('script');
js.src='test.js';
document.getElementsByTagName('head')[0].appendChild(js);
</script>
test.js:
alert('hello, world!');
But this doesn't:
main.htm:
<script>
img = document.createElement('img');
img.src='image.jpg';
document.getElementsByTagName('body')[0].appendChild(img);
</script>
This got me thinking that maybe webbrowsers don't auto-create bodies
for websites whereas they do heads. To test this, I tried to write a
script that'd list all that was created by the browser:
main.htm:
<script>
nodes = document.childNodes;
for (i=0;i<nodes.length;i++)
{
document.write(nodes.nodeTypedValue+'<br />');
}
</script>
Unfortunately, this script just prints out undefined. I tried switched
nodeTypedValue out with node TypeString to no avail.
I then decided to try and modify the second main.htm. I tried making
it look for elements with the tag name of 'head' instead of 'body', but
that didn't help. I tried adding a newly creating body element (whose
bgcolor was black) but that didn't work, either. I even tried adding a
title tag via appendChild to 'head' (whose text was specified by a
createTextNode) but that didn't do anything, either.
So... why can I add javascript files via the method in the first
main.htm when I can't add anything else?
Also, why doesn't the second main.htm work?