This is a very basic question. I have this script:
When the document is being read and parsed by the browser, if there's a script
element that calls document.write
, the output of document.write
is inserted into the document at that point. Later, though, once the page is fully loaded, if you use document.write
, it implicitly performs a document.open
, which wipes out the page and starts writing a new one from scratch.
More on MDN:
In general, rather than using document.write
to add content to a page, use the various DOM methods (either directly, or via a library like jQuery, YUI, Closure, or any of several others).
When it is executed after the page has completed loading, it overwrites the entire content - one of the points raised in the answer to this question: Why is document.write considered a "bad practice"?
document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.