By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,567 Members | 1,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,567 IT Pros & Developers. It's quick & easy.

Mystified....

P: n/a
var body = "blah";
document.getElementById("messagebody").innerHTML = body.toString();

results in syntax error!!!!

Any ideas?
Sep 15 '06 #1
Share this Question
Share on Google+
8 Replies


P: n/a
turnitup wrote:
var body = "blah";
document.getElementById("messagebody").innerHTML = body.toString();

results in syntax error!!!!
No it does not.
Any ideas?
Do you mean runtime error?

Richard.

Sep 15 '06 #2

P: n/a
VK
turnitup wrote:
var body = "blah";
document.getElementById("messagebody").innerHTML = body.toString();

results in syntax error!!!!

Any ideas?
Not a syntax error, but run-time error ("Object is missing" to be
precise).

IMHO it is not the best idea of using "body" as a variable/property
name (as well as "window", "document" and similar).

Apart of that it works just fine, and you don't need to cast primitives
toString(), in string context (such as innerHTML or alert) it will be
done automatically. In fact you almost never need to use toString (but
it is useful to overload it sometimes for custom objects).

The problem is that you are trying to execute your string immediately,
before window.onload event is fired. Until this event is fired, you
cannot use DOM methods, including getElementById (because document's
DOM is not existing yet). The only method you can use to alter the
document content before onload event is document.write (and
respectively never use document.write *after* onload event, as since
that point forward it will clear the current document).

This way you have two options to make your script work:

1) upon onload event:

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function init() {
var body = "blah";
document.getElementById("messagebody").innerHTML = body;
}

window.onload = init;
</script>
</head>

<body>
<p id="messagebody"></p>
</body>
</html>
2) during loading via document.write
(the latter is used only to test features and
insert some extra blocks into document depending
on test results, which is not your case):

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
</head>

<body>
<p id="messagebody">
<script type="text/javascript">
var body = "blah";
document.write(body);
</script>
</p>
</body>
</html>

Sep 15 '06 #3

P: n/a

VK wrote:
turnitup wrote:
var body = "blah";
document.getElementById("messagebody").innerHTML = body.toString();

results in syntax error!!!!

Any ideas?

Not a syntax error, but run-time error ("Object is missing" to be
precise).
[...]
The problem is that you are trying to execute your string immediately,
before window.onload event is fired. Until this event is fired, you
cannot use DOM methods, including getElementById (because document's
DOM is not existing yet).
You can use DOM methods (including getElementById) in scripts placed
immediately after the nodes they wish to access. You don't have to
wait for the entire document to load - the document exists (at least)
from the moment the browser starts to load the content.

The only method you can use to alter the
document content before onload event is document.write
Wrong - see above.

(and
respectively never use document.write *after* onload event, as since
that point forward it will clear the current document).

This way you have two options to make your script work:
Or put the script after the closing tag of the element with id
'messagebody':

<div id="messagebody"></div>
<script type="text/javascript">
var body = "blah";
document.getElementById("messagebody").innerHTML = body;
</script>

[...]

--
Rob

Sep 16 '06 #4

P: n/a
VK
RobG wrote:
You can use DOM methods (including getElementById) in scripts placed
immediately after the nodes they wish to access. You don't have to
wait for the entire document to load - the document exists (at least)
from the moment the browser starts to load the content.
That was a taboo for many years, because placing <scriptright after
the element tag insured only one thing: that the relevant chunk of HTML
source will be *read* by parser before script execution. Whether it
will be properly *parsed* or not to the moment of the script execution:
that depended on the parser algorithms and speed.
Searching c.l.j. for instance will give a good number of "misterious"
cases then blocks
HTML Element
Script handling HTML Element above
failed to work for non-IE browsers or failed to work for the same
browser depending on the document complexity/structure.
In this aspect I see that all UA's I can get on hold at the moment (IE6
SP2, Firefox 1.5.0.6, Opera 8.54) did adopt the IE's mechanics so DOM
is available before finalized.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
</head>

<body>
<p id="output"></p>
<script type="text/javascript">
try {
document.getElementById('output').innerHTML = 'foobar';
window.alert(document.getElementsByTagName('P').le ngth); // 1
}
catch(e) {
window.alert(e.message);
}
</script>
<p id="p01"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam ultrices,
augue ac tincidunt porta, magna sem porta sem, vel ullamcorper libero
metus
ut nunc. Pellentesque feugiat elementum nibh. Phasellus eget enim at
ipsum
facilisis auctor. Quisque nec dui. In ligula. Duis quis pede.
Maecenas venenatis
tellus vitae arcu. Pellentesque odio mauris, fermentum quis, interdum
ut,
blandit hendrerit, massa. Duis ut erat. Donec nec arcu elementum
lacus vehicula
tempus. Praesent vitae velit vel orci ultricies varius. In in eros in
massa
interdum accumsan. Cras tincidunt. Quisque consequat. Duis tincidunt
metus
sit amet libero. Phasellus non massa sit amet diam pulvinar
imperdiet. Aenean
et neque. Nunc luctus.
<p id="p02">Nulla in erat. Cum sociis natoque penatibus et magnis dis
parturient montes,
nascetur ridiculus mus. Aenean eros massa, condimentum a, egestas
quis, tempus
et, est. Aenean eu leo. Vivamus nibh eros, nonummy sed, sollicitudin
at, porta
eget, purus. Aenean et ipsum. Nulla dictum magna id tellus elementum
facilisis.
Suspendisse potenti. Aliquam erat augue, hendrerit cursus, laoreet
vel, egestas
at, ligula. Nullam viverra nibh et purus. Quisque ornare vestibulum
tellus.
Fusce congue. Cras venenatis viverra nunc. Aenean mattis tellus in
nibh. Aenean
adipiscing. Fusce dictum, turpis facilisis tempus tempor, risus nunc
suscipit
magna, vitae iaculis arcu magna sed nunc. Suspendisse venenatis massa
hendrerit
urna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
</body>
</html>
In either case it seems as a non-documented feature as all references
still state that "DOM is not available until the document is loaded".

Thanks for pointing out.

Sep 16 '06 #5

P: n/a

VK написав:
RobG wrote:
You can use DOM methods (including getElementById) in scripts placed
immediately after the nodes they wish to access. You don't have to
wait for the entire document to load - the document exists (at least)
from the moment the browser starts to load the content.

That was a taboo for many years, because placing <scriptright after
the element tag insured only one thing: that the relevant chunk of HTML
source will be *read* by parser before script execution. Whether it
will be properly *parsed* or not to the moment of the script execution:
that depended on the parser algorithms and speed.
I think that placing scripts immediately after the nodes they wish to
access is not good idea. Different browsers acts different. I think
sometimes browser can rebuild DOM after script got reference to node
and when script tries to access node it fails.

Val

Sep 16 '06 #6

P: n/a
VK wrote:
turnitup wrote:
>var body = "blah";
document.getElementById("messagebody").innerHTM L = body.toString();

results in syntax error!!!!

Any ideas?

Not a syntax error, but run-time error ("Object is missing" to be
precise).
<snip>

In the last week you have demonstrated that you fall foul of drawing
false conclusions by misinterpreting the evidence you have. Your error
here is probably worse as you have drawn a conclusion in the absence of
any evidence that would support it at all. It may be the case that in
certain contexts the above two lines of code could result in an 'object
expected' error, but so many other errors could also happen in
association with that code that making any one specific assertion of
cause and effect without the context is irrational.

Richard.
Sep 17 '06 #7

P: n/a
sc********@gmail.com wrote:
<snip>
I think that placing scripts immediately after the nodes
they wish to access is not good idea.
That would probably depend a great deal on what was being attempted. If
the desire was to pick up a reference to an element for later use, or
the direct assignment to an elements style object, then there is
unlikely to be a problem (at least where the code is sufficiently
defensive). A desire to do things like measure the dimensions/position
of an element are unlikely to be successful prior to the onload event,
as the parsing of subsequent elements may influence layout so even if
provisional information is available no final layout could be available
until the entire document has been parsed. And re-arranging the DOM at
that point certainly will fail on browsers such as Opera 7.
Different browsers acts different.
But not necessarily so differently that some things would not be viable
for inline scripts.
I think sometimes browser can rebuild DOM after script
got reference to node and when script tries to access
node it fails.
Thinking something is not the same as having a test case that
demonstrates it. It is worth asking what an HTML parser may encounter as
it reads past an element that may make it re-structure the DOM it is
building. The DOM, after all, mirrors in structure the tree-like form of
structurally valid HTML.

However, one thing that an HTML parser may encounter that would
encourage it to re-structure the DOM would be structurally invalid
mark-up. It has, for example, been demonstrated that misplaced FORM tag
result in most browser creating structurally divergent DOMs as they
attempt to error-correct the document, and a misplaced FORM tag may not
have been seen at the point of executing an inline script.

This may mean that if a browser could be demonstrated to be
re-arranging/re-building its DOM during the parsing of an HTML document
that re-structuring could be directly attributed to its being presented
with structurally invalid mark-up and having to error-correct it. At
which point the solution is not to adopt a bogus 'do not access DOM
elements while the DOM is being built" rule, but instead to adopt an
"only attempt to script structurally valid mark-up" rule.

That is, the sensible response is to see the demonstration of the issue,
accurately identify case and effect relationships, and make judgements
based upon that knowledge. The alternative is programming by rumours,
hearsay, mystical incantation and voodoo.

Richard.
Sep 17 '06 #8

P: n/a
Richard Cornford wrote:
>I think that placing scripts immediately after the nodes
they wish to access is not good idea.
That would probably depend a great deal on what was being attempted.
If the desire was to pick up a reference to an element for later use,
or the direct assignment to an elements style object, then there is
unlikely to be a problem (at least where the code is sufficiently
defensive).
I've not seen a recent browser that doesn't make DOM elements available to
script as soon as they appear in the page, but I've also never seen anything
in any standards that suggests that this behavior is required. So in theory
a future browser might make the DOM unavailable until all the HTML has been
parsed.

In order to be sufficiently defensive, you would need to access the DOM both
right away and after the page is loaded, with the second access first
checking to see if the first access was successful. Or is there a better
way? Seems like a lot of extra work!

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Sep 18 '06 #9

This discussion thread is closed

Replies have been disabled for this discussion.