jQuery several external HTML elements under a single DIV container
my goal is to load three distinct div elements from an external HTML and insert it under the same div container of the parent HTML by using jQuery.
Currently, my code looks as follows (external HTML, excerpt):
<div id="wrapper">
<div id="content">Main.</div>
<div id="rightcolumn">Right.</div>
<div id="legendcolumn">Legend.</div>
</div>
And I would like to insert all three div elements under div id="inserted" into the parent HTML. In jQuery I found the load() function. However, it replaces all the content under the element and doe开发者_JS百科s not append it.
$("#inserted").load("external.html #wrapper");
This code replaces all previous elements under body.
You can use the $.get
or $.post
ajax functions instead of the .load()
function, which was designed to do one thing and one thing only. Your code will look something like this:
$.get('external.html', function(data){
$(data).find('#wrapper > div').appendTo('#inserted');
});
external.html
will be accessible through the data
variable, so we wrap it with the jQuery function, then find the elements we need before appending them to the correct element in the current page.
精彩评论