Click to See Complete Forum and Search --> : document.write()
AntonioMainenti
02-18-2003, 12:44 PM
This is a problem I've been having for a long time, and now I am hoping to straighten this out.
I'm making a table with JavaScript, like this:
document.write("<table>");
for (x=0;x<table_height;x++)
{
document.write("<tr>");
for (y=0;y<table_width;y++)
{
td="blah blah blah";
document.write("<td>"+td+"</td>");
}
document.write("</tr>");
}
document.write("</table>");
But the problem is that document.write() seems to wipe out the rest of the code in the document, so all my functions are gone! I have no idea how to fix it.
Thanks, Alan.
gil davis
02-18-2003, 01:08 PM
If you are using that code after the page has loaded, then that is why it wipes out the rest of your code. After the document has loaded, the document is closed. If you use document.write on a closed document, it does a document.open for you and erases the existing document.
AntonioMainenti
02-18-2003, 01:19 PM
Ok, I understand that, but what I would like to know is how to write HTML code with JavaScript without wiping out the rest of the page.
Thanks, Alan.
gil davis
02-18-2003, 02:42 PM
You can extrapolate from my post that as long as the document is not closed, you can safely use document.write. This means that scripts dispersed in the HTML that contain document.write instructions will not wipe out the rest of the document. Scripts that are activated after the load process has completed, will wipe out the document.
The newer W3C DOM compliant browsers support ways to create new HTML objects as required and do not involve using document.write.
IE 4+ and NS 6+ support "innerHTML" that will allow you to replace parts (or all) of the HTML.
NS 4 does not support "innerHTML", and you must use document.write. However, the NS 4 DOM is such that any positioned object has it's own document, separate from the main document. So there is a way to contain the writing to a particular layer's document without wiping out the rest of the document.
The most correct technique would depend on your intent. Why are you using document.write, and what are you writing?