Zoinky
Zoinky

Reputation: 4999

jquery insert BEFORE last element in div

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

Upvotes: 8

Views: 10965

Answers (1)

Alpha Codemonkey
Alpha Codemonkey

Reputation: 3261

$('#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.

Upvotes: 17

Related Questions