Dynamically Generated Documents
One of the
most important features of the
Document object (and perhaps of client-side JavaScript in general) is
the write( )
method, which allows you to
dynamically generate web-page content from your JavaScript programs.
This method can be used in two ways. The first and simplest way to
use it is within a script, to output dynamically generated
HTML into the document that is
currently being parsed. This was discussed in Chapter 12. Consider the following code, which uses
write( )
to add the current
date and the document’s
last-modified date to an otherwise static HTML document:
<script> var today = new Date( ); document.write("<p>Document accessed on: " + today.toString( )); document.write("<br>Document modified on: " + document.lastModified); </script>
Using the write( )
method in this way is an
extremely common JavaScript programming technique, and you’ll
see it in many scripts.
Be aware, however, that you can use the write( )
method to output HTML to the current document only while that
document is being parsed. That is, you can call
document.write( )
from within
<script>
tags only because
these scripts are executed as part of the document parsing process.
In particular, if you call document.write( )
from within an event handler and that handler is invoked once the document has already been parsed, you will end up overwriting the entire document (including its event handlers), instead of appending text to it. The reason for this will become ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.