Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does document.write() do?

Tags:

javascript

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.

like image 710
Akhil Sekharan Avatar asked Dec 06 '12 10:12

Akhil Sekharan


1 Answers

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).

like image 115
T.J. Crowder Avatar answered Nov 08 '22 09:11

T.J. Crowder