FarFar
FarFar

Reputation: 141

Add html to an html file that was previously loaded with jQuery?

Suppose I have loaded an html file using the jQuery .load function into another html file. The loaded html file has a div of id random_div. Is it possible, for example, the html <div id="loaded_html_div"></div> into the #random_div?

Here is what I've come up with:

$(document).ready(function(){
    // random.html has the div of id random_div
    $('#html_container').load('random.html');

    $('#random_div').html('<div id="loaded_html_div"></div>');
)};

I've also tried

$('#random_div').append('<div id="loaded_html_div"></div>');
$('#random_div').load('<div id="loaded_html_div"></div>');

They don't work either.

Thanks!

Upvotes: 0

Views: 66

Answers (2)

Jaymin Panchal
Jaymin Panchal

Reputation: 2856

You have to append div after another file successfully loads.

$(document).ready(function(){
    $('#html_container').load('random.html', function(){
        // Whatever you want to add in #random_div.
        $('#random_div').html('<div id="loaded_html_div"></div>');
    });    
});

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

You are trying to add HTML before the element is loaded since ajax is an asynchronous process. So do it within the success callback of load() method.

$(document).ready(function(){
    $('#html_container').load('random.html'function(){
        $('#random_div').html('<div id="loaded_html_div"></div>');
    });    
});

Upvotes: 1

Related Questions