1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!


Join the Discussion

Questions? Comments?

A lot of people, particularly those first starting out with Javascript use document.write to write things into their web page. I use this method in the early Learn Javascript tutorials because it is the easiest way to get Javascript to write something into the page when the page is first created.

document.write('Hello World');

Being the easiest way to write HTML out from Javascript doesn't mean that it is the best way to write HTML from Javascript or even that it will work in all situations. In fact the document.write method is very limited in what you can do with it.

To start with document.write only works with pages that the browser processes as HTML. Pages the browser processes as XML cannot use document.write at all. Pages defined with an XHTML DOCTYPE should be served as XML rather than HTML however Internet Explorer versions prior to version 7 have a problem with displaying those pages properly in the first place and so HTML needs to be used for that browser. That could lead to your configuring your page to be handled differently in different browsers meaning that document.write will then only work in Internet Explorer.

If you didn't understand that last paragraph don't worry as the situation probably doesn't apply to you. It describes a more advanced situation where you can't use document.write at all.

The next thing to concern yourself with is that document.write statements must be run before the page finishes loading. This means that they must be either in the body of the page or in functions called from the body of the page. So the following is acceptable:

<script type="text/javascript">
function w1() {
document.write('hello world');
<script type="text/javascript">
document.write('goodbye moon');

Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. This is almost certainly not what you intend to have happen. You should therefore avoid using document.write in situations such as this:

<script type="text/javascript">
function w1() {
document.write('hello world'); // overwrite entire page
window.onload = w1;

So you can only use document.write at best to write the original content of your page. It cannot be used to update the content of your page after that page has loaded.

Updating an already loaded web page requires a knowledge of how to use the Javascript Document Object Model

©2016 About.com. All rights reserved.