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
scriptelement that callsdocument.write, the output ofdocument.writeis inserted into the document at that point. Later, though, once the page is fully loaded, if you usedocument.write, it implicitly performs adocument.open, which wipes out the page and starts writing a new one from scratch.More on MDN:
document.writedocument.openIn general, rather than using
document.writeto 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).