Bart Blarft
Bart Blarft

Reputation: 45

table append without last element

    ​<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

Answers (4)

David Thomas
David Thomas

Reputation: 253456

Use insertBefore():

$('#add').click(function(){
   $('<tr><td>one</td><td>two</td></tr>').insertBefore('#sum');
})​

JS Fiddle demo.

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>');
})​

JS Fiddle demo.

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>');
})​

JS Fiddle demo.

References:

Upvotes: 7

Just do:

$('#sum').before('<tr><td>one</td><td>two</td></tr>');

Upvotes: 1

Giona
Giona

Reputation: 21114

Really simple :) use before

$('#add').click(function(){
   $('#sum').before('<tr><td>one</td><td>two</td></tr>');
})​;

Upvotes: 1

Muthu Kumaran
Muthu Kumaran

Reputation: 17920

You can use .before()

$('#add').click(function(){
   $('#sum').before('<tr><td>one</td><td>two</td></tr>');
})​

Upvotes: 1

Related Questions