Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append element not to end, before last element in jQuery

I'm trying to post comment with an AJAX post. But last comment element contains submit button. And after appending, new item appears after submit button.

<div class="commentContainer" >

    <div class="comment">
        <div class="commentText">Any comment1 ... </div>
    </div>

    <div class="comment">
        <div class="commentText">Any comment2 ... </div>
    </div>
        ....................................
    <div class="comment"> 
        <div class="sendPanel">
            <input type="submit" value="Post" />
        </div>
    </div>

</div>

and result of posting request:

success: function (result)  {
    if (result.success) {
         $('.commentContainer').append('<div class="comment"><div class="commentText">' + result.text + '</div></div>');
    }   
} 

I want to keep submit button on the end always. How can I do this?

like image 467
Jeyhun Rahimov Avatar asked Jul 14 '13 17:07

Jeyhun Rahimov


1 Answers

Try this

  $('<div class="comment"><div class="commentText">' + result.text + '</div></div>')
   .insertBefore('commentContainer .comment:last-child'); 

Or even better

$('<div>', {'class': 'comment'}).append(
    $('<div>', {'class': 'commentText', text: result.text})
).insertBefore('.commentContainer .comment:last-child');

This one is better for performance

Demo

jQuery last-child

jQuery insertBefore

like image 134
iConnor Avatar answered Sep 27 '22 23:09

iConnor