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 ?

1
  • Do you want to add the row to end of tbody? Commented Dec 23, 2009 at 13:40

2 Answers 2

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is not working for me in IE8. Basically, it results in this HTML: "<TR> 1</TD><//TD> <TD> </TD> a</TD><//TD></TR><//TR> </TR>" Idea? Thanks.
sure, I posted the issue here, stackoverflow.com/questions/2329319/…
1
if( !$('#myTable tbody').length )
{
  $('#myTable').append( $('<tbody>') );
}

$('#myTable tbody').append( '<tr><td>1</td><td>a</td></tr>' );        

1 Comment

I think this won't add rows to the inner of thead or tbody.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.