In jQuery, how to load ajax content after specified element
I have the following HTML:
<div id="mydiv">
</div>
I would like to load the content using jQuery so that it appears after my DIV.
I've tried this:
$("#mydiv").load("/path/to/content.html");
However, it ends up with this result:
<div id="mydiv">
<p>content from file</p>
</div>
How do you get this result?
<div id="mydiv">
</div>
<p>content from file<p>
source to share
If you are still looking for a solution, I would suggest using AJAX jQuery.get()
instead .load()
to load the content. Then use a .after()
function to specify the previous item.
Here's an example:
$.get('url.html', function(data){ // Loads content into the 'data' variable.
$('#mydiv').after(data); // Injects 'data' after the #mydiv element.
});
source to share
I have one interesting, but rather complex and understandable method, but using the .load function. So the code:
$('#div_after').remove();
$('#mydiv').after($('<div>').load('/path/to/content.html #div_after', {
data: data, //variables to send. Useless in your case
}, function () {
$(this).children().unwrap();}
));
See, I am applying the .remove () method to remove a previously created div if you use this code more than once. You can remove the first line if it will only be used once. The idea of .after ($ '') creates a noname div on the page after #mydiv and .load () html into it with a callback function
$(this).children().unwrap();
which logically expands into our noname div and "renames" it to our #div_after from the html load. It is also unnecessary if you only want to use an unnamed div.
Hooray!
PS It took me a while in the project to put it all together :) I wish this was useful.
source to share