Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A very basic JavaScript question about the document.write function

I'm new to JavaScript as well as jQuery. This is the only code I have on an otherwise blank page:

<script type="text/javascript" src="jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            document.write('Hello World');

        });
    </script>

When I load the page in a browser (using FireFox) the status icon as well as the favicon area of the opened tab shows loading symbols, as if to indicate that the document.write function is being executed continuously in a loop.

Why is this? I'm merely trying to say "once the page is ready output to the screen the string Hello World ONCE". What's wrong here?

p.s. I noticed if I take out the document.ready portion of the code there is no loop. Not sure why the event ready handler is causing this issue.

like image 358
Jake Avatar asked Nov 22 '25 04:11

Jake


1 Answers

document.write, if executed after the DOM is loaded, completely rewrites the page. It can only be executed while the DOM is loading, not after, and $(document).ready() occurs after the DOM has completed loading.

You're looking to append().

<script type="text/javascript">
    $(document).ready(function() {

        $('body').append('Hello World');

    });
</script>
like image 55
Yahel Avatar answered Nov 23 '25 18:11

Yahel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!