This is a very basic question. I have this script:
<script type="text/javascript">
function write(){
document.write('Hello2')
}
write();
</script>
It shows my complete page. And at the end of page Hello2 will be displayed. But when ever I go to developer tools and call write(), it will replace my entire body html. Just curious to know.
window.onload=write;// has the same effect. Clear's my page.
Thanks.
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:
document.write
document.open
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With