omg
omg

Reputation: 139982

How can jQuery load some html and append it to the <body> element?

I tried the following:

$.load("Views/chatBox.html").appendTo('body')

Console Output:

TypeError: $.load is not a function 

EDIT: The answer should only be one line of code; that's enough, I think.

Upvotes: 23

Views: 85140

Answers (5)

Kirill Fuchs
Kirill Fuchs

Reputation: 13696

An alternative solution:

jQuery('#AppendToMe').append( jQuery('<div>').load(...) );

This will append whatever you load into the #AppendToMe element.

Upvotes: 3

Rob Evans
Rob Evans

Reputation: 6968

Nope, all those answers are incorrect because they rely on having a separate container!

Do this:

$.ajax({
    url: "your.html",
    success: function (data) { $('body').append(data); },
    dataType: 'html'
});

Upvotes: 83

waffles
waffles

Reputation: 41

When I tried out GaVrA's solution I found it could be even simpler:

<script type="text/javascript">
    $(function() {
        $("#container").load("external.html").appendTo("body");;        
    });
</script>

I guess appentTo automatically removes a previous instance? Perhaps I'm missing something here?

Upvotes: 1

Gavrisimo
Gavrisimo

Reputation: 1837

I dont understand why placing container at the bottom of body and loading external page into that is not what you need?

What you can try is this:

<script type="text/javascript">
    $(function() {
        $("#container").load("Views/chatBox.html",function(){
            $(this).clone().appendTo("body").remove();
        });
    });
</script>

But im not 100% sure about this code... :)

Upvotes: 9

Gavrisimo
Gavrisimo

Reputation: 1837

Here you go:

<script type="text/javascript">
    $(function() {
        $("body").load("Views/chatBox.html");
    });
</script>

Upvotes: -1

Related Questions