x.innerHTML would contain everything between the <body>
tags (see below), so by calling document.write(x.innerHTML), you're
also re-inserting the JS code into the web document.
x.innerHTML:
<
P>Hello World!< /P>
< DIV> < P>The DOM is very useful!< /P>
< P>This example demonstrates the < B>document.body<
/B> property.< /P>
< /DIV>
< SCRIPT TYPE="text/Javascript">
x=document.body;
alert(x.innerHTML);
document.write(x.innerHTML);
< /SCRIPT>
As you can see, this would
result in the browser parsing the same JS code again, resulting in
a loop.
If you wish to display the
code on the web page, you'll need to convert the special characters
(such as < and >) to HTML entities so that the browser would
recognize them as text rather than HTML code and parse them. You
may wish to use the following JS function for this
purpose:
http://phpjs.org/functions/htmlspecialchars:426