In tutorials I've learnt to use document.write
. Now I understand that by many this is frowned upon. I've tried print()
, but then it literally sends it to the printer.
So what are alternatives I should use, and why shouldn't I use document.write
? Both w3schools and MDN use document.write
.
The reason that your HTML is replaced is because of an evil JavaScript function: document.write()
.
It is most definitely "bad form." It only works with webpages if you use it on the page load; and if you use it during runtime, it will replace your entire document with the input. And if you're applying it as strict XHTML structure it's not even valid code.
document.write
writes to the document stream. Callingdocument.write
on a closed (or loaded) document automatically callsdocument.open
which will clear the document.
document.write()
has two henchmen, document.open()
, and document.close()
. When the HTML document is loading, the document is "open". When the document has finished loading, the document has "closed". Using document.write()
at this point will erase your entire (closed) HTML document and replace it with a new (open) document. This means your webpage has erased itself and started writing a new page - from scratch.
I believe document.write()
causes the browser to have a performance decrease as well (correct me if I am wrong).
This example writes output to the HTML document after the page has loaded. Watch document.write()
's evil powers clear the entire document when you press the "exterminate" button:
I am an ordinary HTML page. I am innocent, and purely for informational purposes. Please do not <input type="button" onclick="document.write('This HTML page has been succesfully exterminated.')" value="exterminate"/>
me!
.innerHTML
This is a wonderful alternative, but this attribute has to be attached to the element where you want to put the text. Example: document.getElementById('output1').innerHTML = 'Some text!';
.createTextNode()
is the alternative recommended by the W3C. Example: var para = document.createElement('p');
para.appendChild(document.createTextNode('Hello, '));
NOTE: This is known to have some performance decreases (slower than .innerHTML
). I recommend using .innerHTML
instead.
.innerHTML
alternative:I am an ordinary HTML page.
I am innocent, and purely for informational purposes.
Please do not
<input type="button" onclick="document.getElementById('output1').innerHTML = 'There was an error exterminating this page. Please replace <code>.innerHTML</code> with <code>document.write()</code> to complete extermination.';" value="exterminate"/>
me!
<p id="output1"></p>