Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery insert BEFORE last element in div

Tags:

jquery

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

like image 732
Zoinky Avatar asked Feb 25 '14 23:02

Zoinky


People also ask

How to append after last child jQuery?

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.

How to insertBefore in jQuery?

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 do you insert before an element?

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.

What is prepend in jQuery?

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.


1 Answers

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

like image 150
Alpha Codemonkey Avatar answered Sep 23 '22 10:09

Alpha Codemonkey