Reputation: 45
<table id="table">
<tr><td>one</td><td>two</td></tr>
<tr id="sum"><td>sum</td><td>sum2</td></tr>
</table>
<span id="add">add new</span>
$('#add').click(function(){
$('#table').append('<tr><td>one</td><td>two</td></tr>');
})
How can i make that this add new element with append as penultimate element? I would like that #sum still are last element.
Upvotes: 1
Views: 405
Reputation: 253456
Use insertBefore()
:
$('#add').click(function(){
$('<tr><td>one</td><td>two</td></tr>').insertBefore('#sum');
})
You could also simply use multiple tbody
elements, one to contain the #sum
row, and the others for the, in this example, #content
:
<table id="table">
<tbody id="content">
<tr><td>one</td><td>two</td></tr>
</tbody>
<tbody>
<tr id="sum"><td>sum</td><td>sum2</td></tr>
</tbody>
</table>
With the jQuery:
$('#add').click(function(){
$('#content').append('<tr><td>one</td><td>two</td></tr>');
})
Or, possibly, using a tfoot
(though I'm not sure that this a proper use-case for a tfoot
element:
<table id="table">
<tfoot>
<tr id="sum"><td>sum</td><td>sum2</td></tr>
</tfoot>
<tbody id="content">
<tr><td>one</td><td>two</td></tr>
</tbody>
</table>
And jQuery:
$('#add').click(function(){
$('table tbody').append('<tr><td>one</td><td>two</td></tr>');
})
References:
Upvotes: 7
Reputation: 50623
Just do:
$('#sum').before('<tr><td>one</td><td>two</td></tr>');
Upvotes: 1
Reputation: 21114
Really simple :) use before
$('#add').click(function(){
$('#sum').before('<tr><td>one</td><td>two</td></tr>');
});
Upvotes: 1
Reputation: 17920
You can use .before()
$('#add').click(function(){
$('#sum').before('<tr><td>one</td><td>two</td></tr>');
})
Upvotes: 1