0

I am using this to add a row dynamically to a table:

   $('#myTable tr:last').after('<tr><td>1</td><td>a</td></tr>');

but it doesn't seem to work if the table has no records:

<table id="myTable" class="altTable">
    <thead>
        <tr>
            <th>
                Col1
            </th>
            <th>
                Col2
            </th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

what would be the right selector here to add a row that would work if there are 0 or > 0 rows existing ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
leora
  • 188,729
  • 360
  • 878
  • 1,366

2 Answers2

9

Try this...

$("<tr><td>1</td><td>a</td></tr>").appendTo("#myTable tbody");

That should add a row to the end of the table body tag regardless of if there are rows there already or not.

If the tbody tag won't be present w/o any rows already there then you would do this...

if ($("#myTable tbody").length > 0){
  $("<tr><td>1</td><td>a</td></tr>").appendTo("#myTable tbody");
}
else{
  $("<tbody><tr><td>1</td><td>a</td></tr></tbody>").appendTo("#myTable");
}
Ryan
  • 6,756
  • 13
  • 49
  • 68
  • This is not working for me in IE8. Basically, it results in this HTML: " 1/TD> a/TD>/TR> " Idea? Thanks. – Ariel Feb 24 '10 at 20:26
  • sure, I posted the issue here, http://stackoverflow.com/questions/2329319/javascript-issue-when-dynamically-adding-a-row-from-its-html-to-a-table-in-ie – Ariel Feb 26 '10 at 12:09
1
if( !$('#myTable tbody').length )
{
  $('#myTable').append( $('<tbody>') );
}

$('#myTable tbody').append( '<tr><td>1</td><td>a</td></tr>' );        
leora
  • 188,729
  • 360
  • 878
  • 1,366
Anwar Chandra
  • 8,538
  • 9
  • 45
  • 61