Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata