473,396 Members | 1,998 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,396 software developers and data experts.

Mystified....

var body = "blah";
document.getElementById("messagebody").innerHTML = body.toString();

results in syntax error!!!!

Any ideas?
Sep 15 '06 #1
8 1372
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
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

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
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

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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Ben Thomas | last post by:
Hi all, I'm having some trouble understanding the behavior of std::ostringstream. (I'm using Visual Studio .Net & STL port 4.5.3). I'll appreciate if someone can give me a little explanation of...
1
by: Tom Yee | last post by:
We just installed SQL Server version 800.194 on a dual processor server equipped with a gigabyte of RAM, running Windows 2000 Server operating system. We set up a few databases with (so far) very...
3
by: Paul Wake | last post by:
http://www.xmission.com/~wake/section27.html now works for me in IE/Win but not in Mozilla/Win (my PowerBook is dead and I'm now using my mother-in-law's PC, which limits my options for checking...
1
by: Joost | last post by:
Hi to all, I have a subform which changes its Sourceobject, using the following expression: Forms!!.SourceObject = "Subform Deposito Mant" and the focus to the desired control, a textbox...
12
by: Chad | last post by:
This was taken from the following: http://groups.google.com/group/comp.lang.c/browse_thread/thread/089dfb62c71802b3/663e9afae83d061c?hl=en#663e9afae83d061c And I quote: "Well, that's also ok...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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 projectplanning, coding, testing,...

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.