I am getting back some data using ajax and I would like to insert it as the second last child of a div
., Question is how do i insert some html into a div before the last element in that div
$.ajax({
url: '@Url.Action("...", "..")',
traditional: true,
data: { coordinates: coordinates, selectedTypeIDs: selectedTypeIDs, pageNumber: pageNumber },
type: 'POST',
success: function (data) {
$('#listings').insertBefore(".last-child", data);
hideProgress();
},
error: function (xhr, textStatus, errorThrown) {
showErrorMessage("Something whacky happened", errorThrown);
}
Here is my div
and in it a comment that shows where I want to put it
<div id="listings">
<!--bunch of divs-->
<div>something</div>
<!--INSERT DATA HERE-->
<div class="black_box2" id="showMoreBar"></div>
</div>
I could either use the class name black_box2
or better yet, the id i assigned to the last div
, or what ever is faster way of doing it
To insert element as a last child using jQuery, use the append() method. The append( content ) method appends content to the inside of every matched element.
jQuery insertBefore() MethodThe insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.
How it works. First, get the menu element using the getElementById() method. Second, create a new list item using the createElement() method. Third, insert the list item element before the first child element of the menu element using the insertBefore() method.
The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.
$('#listings').insertBefore(".last-child", data);
would put #listings
before .last-child
(theres no second paramter for insertBefore).
What you want is:
$("#showMoreBear").before(data); // put data before #showMoreBear
Or
$(data).insertBefore('.last-child'); // put data before .last-child
.before( content ) places the content before the selected element.
.insertBefore( target ) places the selected element before the target.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With