Reputation: 1173
I'd like to add item 3 before add. How do I do it? I thought about using index but then I still didnt know how to append it even if I knew where it should be placed. Anyways here is my demo
HTML:
<div id="main">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="Add">Add</div>
</div>
JS:
$('<div class="item">Item 3</div>').appendTo('#main');
Upvotes: 11
Views: 16643
Reputation: 253318
I'd suggest:
$('<div class="item">Item 3 (inserted item)</div>').insertBefore('div.Add');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="main">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="Add">Add</div>
</div>
Or:
$('<div class="item">Item 3 (inserted item)</div>').insertAfter('.item:last');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="main">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="Add">Add</div>
</div>
Though I'd suggest changing the syntax in the node-creation to:
$('<div />', {
class: 'item',
text: 'Item 3 (inserted item)'
}).insertAfter('.item:last');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="main">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="Add">Add</div>
</div>
I find it just a little easier to read that way (though definitely not mandatory, or even 'best-practice').
As of editing the answer – to include the Stack Snippets – this is all easily achievable with plain JavaScript:
// using Object.assign() to create an Object from the
const newDivElement = Object.assign(
// merger of the Element Object created
// by document.createElement():
document.createElement('div'),
// and the properties specified in the
// separate Object:
{
className: 'item',
textContent: 'Item 3 (inserted item)',
});
// using an Array literal along with the spread operator to
// convert the iterable NodeList returned by
// document.querySelectorAll() into an Array of element nodes,
// in order to use Array methods to find the last .item element:
[...document.querySelectorAll('.item')]
// using Array.prototype.map() to remove - and return - the
// last Array element, which is the last .item element:
.pop()
// and then using Element.after() to insert the newDivElement
// after that last .item:
.after(newDivElement);
<div id="main">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="Add">Add</div>
</div>
References:
Upvotes: 22
Reputation: 161
This works by finding the second last div within #main
var newItemHTML = '<div class="item">Item 3</div>',
$secondLast = $('#main').find('div:last-child').prev();
$( newItemHTML ).insertAfter( $secondLast );
Upvotes: 1
Reputation: 3765
You could append after the last .item
:
$('.item').last().after($('<div class="item">Item 3</div>'));
Upvotes: 2