473,398 Members | 2,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

trouble adding elements via DOM

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[i].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?

Mar 15 '06 #1
5 1857


yawnmoth wrote:

But this doesn't:

main.htm:
<script>
img = document.createElement('img');
img.src='image.jpg';
document.getElementsByTagName('body')[0].appendChild(img);
</script>


How about writing valid HTML 4 first and then manipulate the DOM, making
sure that there is a body element before you try to insert any element
into it.
Or do you have a requirement to write minimal HTML snippets and hope the
browser adds the missing structure?

--

Martin Honnen
http://JavaScript.FAQTs.com/
Mar 15 '06 #2
yawnmoth said the following on 3/15/2006 1:04 PM:
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:
No, they auto-create whatever container they need. In both cases, it
creates the HEAD element because you left it out and it needed it to
place the script element in. Use a properly validated HTML file and both
of your scripts work as long as the second is in a function or in the
body element.

To see the body get created auto, in your second example, add some HTML:

<p>content</p>
<script code here>

And it will work.

What you *should* have gotten from the second example was an error message:
IE:
document.getElementsByTagName(...).0 is null or not an object
Firefox:
Error: document.getElementsByTagName("body")[0] has no properties
<snip>
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?


See Above. But it's because you are not using valid HTML and expecting
valid results.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 15 '06 #3

Randy Webb wrote:
yawnmoth said the following on 3/15/2006 1:04 PM:
<snip>
No, they auto-create whatever container they need. In both cases, it
creates the HEAD element because you left it out and it needed it to
place the script element in.

Well then, what other elements does it auto-create? The script I wrote
didn't tell me, so what will?

You also suggest that the second main.htm didn't work because there
wasn't any valid HTML. I don't understand that - even in scripts with
valid HTML, new elements can be added via the DOM that don't,
explicitly, have any HTML, themselves. Why are these accessable while
they aren't in the second main.htm that I posted?

Mar 15 '06 #4
yawnmoth wrote:
Randy Webb wrote:
yawnmoth said the following on 3/15/2006 1:04 PM:
<snip>
No, they auto-create whatever container they need. In both cases, it
creates the HEAD element because you left it out and it needed it to
place the script element in.
Well then, what other elements does it auto-create? The script I wrote
didn't tell me, so what will?


The HTML specification is a start. There are lots of optional *tags* where
the element is mandatory, e.g. html, head and body tags. Also tbody tags
in a table.

If you omit the tags, then you leave it up to the browser to insert the
elements where it sees fit, which may not be where you expect them to occur.

You also suggest that the second main.htm didn't work because there
wasn't any valid HTML. I don't understand that - even in scripts with
valid HTML, new elements can be added via the DOM that don't,
explicitly, have any HTML, themselves. Why are these accessable while
they aren't in the second main.htm that I posted?


I would guess that the browser thinks your script element is in the head
and creates one. Adding a script element to the head therefore 'works'.
When you try to access the body element, it hasn't created one yet so it
barfs (hint - check out the title element).
--
Rob
Mar 15 '06 #5
yawnmoth said the following on 3/15/2006 3:09 PM:
Randy Webb wrote:
yawnmoth said the following on 3/15/2006 1:04 PM:
<snip>
No, they auto-create whatever container they need. In both cases, it
creates the HEAD element because you left it out and it needed it to
place the script element in. Well then, what other elements does it auto-create? The script I wrote
didn't tell me, so what will?


Did you test my suggestion with the <p>content</p>?
When your image script is prefixed with the <p>content</p> then the
browser creates the body element because you didn't and content only
goes in the body - so - it creates one.

Test it.

<script>
img = document.createElement('img');
img.src='image.jpg';
document.getElementsByTagName('body')[0].appendChild(img);
</script>

Gives the two errors - in two different browsers - that I gave you.
Simply put some content ahead of it:

<p>Some Content</p>
<script>
img = document.createElement('img');
img.src='image.jpg';
document.getElementsByTagName('body')[0].appendChild(img);
</script>

Now, your script creates the image and loads it (At least in IE6 and
Firefox) and without errors.
You also suggest that the second main.htm didn't work because there
wasn't any valid HTML.
Not that there "wasn't any valid HTML" but that using a valid HTML
document would have cured the error.
I don't understand that - even in scripts with
valid HTML, new elements can be added via the DOM that don't,
explicitly, have any HTML, themselves. Why are these accessable while
they aren't in the second main.htm that I posted?


Because you are confusing the HTML DOM with what's in the script block.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 16 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Greg | last post by:
I have the following code (a one line function) I'm trying to calculate a value for text field matPerPiece# where # is a row number I provide. The value is calculated from text fields...
34
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and...
2
by: rubikzube* | last post by:
I'm new to mysql and I was wondering if I could trouble some of you for help. I have a table in my database that may contain multiple versions of the same element as different rows. I wanted to...
14
by: Paul_Madden via DotNetMonster.com | last post by:
Basically I have a listbox to which I add simple STRING items- I have a progress bar which I increment whenever I populate another portion of the complete set of items I wish to add. What I observe...
9
by: =?Utf-8?B?Sm9obiBCYWlsZXk=?= | last post by:
I have a ASP .Net page that allows moving around items on the page through javascript. This page works fine in IE. In FireFox however, I have found that if the page is using XHTML 1.0...
6
by: nanodust | last post by:
hello all i am relatively new to python, catching on, but getting stuck on simple thing: i have two string bytes i need to push into a single (short) int, like so in c: temp = strBuf;
18
omerbutt
by: omerbutt | last post by:
AJAX PROB WITH MULTIPLE RECORDS helo iam having problem in ma code will any body look out an help, i am trying t add sale record in the database and the checkthe quantity of the part slod and...
6
by: santiago | last post by:
I guess one cannot do this: arraytot = arraytot + arraydet; So, what's the trick to adding arrays like this? Thanks.
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.