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');
I'd suggest:
$('<div class="item">Item 3</div>').insertBefore('div.add');
Or:
$('<div class="item">Item 3</div>').insertAfter('.item:last');
Though I'd suggest changing the syntax in the node-creation to:
$('<div />',{class: 'item', text: 'Item 3'})
I find it just a little easier to read that way (though definitely not mandatory, or even 'best-practice').
References:
insertAfter()
.insertBefore()
.You could append after the last .item
:
$('.item').last().after($('<div class="item">Item 3</div>'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With