'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?
Solution 1:[1]
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
Solution 2:[2]
You can use the :last pseudo-selector:
try this:
success: function (result)
{
if (result.success)
{
$('.commentContainer').find('div:last').before('<div class="comment"><div class="commentText">' + result.text + '</div></div>');
}
}
Solution 3:[3]
Try this :
success: function (result)
{
if (result.success)
{
$('<div class="comment"><div class="commentText">' + result.text + '</div></div>').insertBefore('.commentContainer .comment:last');
}
}
Solution 4:[4]
I know this question specifically asked about jQuery but this can be done with plain JS quite neatly, with the insertBefore() function, MDN. (I came across this post while looking for a solution to a similar problem but not using jQuery)
ul = document.getElementById('my-list-id'); //Get the list from the DOM
li = document.createElement('li'); // Create the element to append
ul.insertBefore(li, ul.lastChild); // Append the element before the last child
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Alessandro Minoccheri |
| Solution 3 | Kiran Ruth R |
| Solution 4 | Tyler2P |
