Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery append as 2nd last

Tags:

jquery

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');
like image 280
BruteCode Avatar asked Mar 08 '13 23:03

BruteCode


2 Answers

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().
like image 156
David Thomas Avatar answered Sep 30 '22 02:09

David Thomas


You could append after the last .item:

$('.item').last().after($('<div class="item">Item 3</div>'));
like image 33
cjc343 Avatar answered Sep 30 '22 01:09

cjc343