[Solved-5 Solutions] Add table row in jQuery - javascript tutorial



Problem:

How to add table row in jquery ?

Solution 1:

For Example:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

Using this code:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

We would recommend this approach instead:

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

We can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.

$('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');

Solution 2:

jQuery got a built-in facility to manipulate DOM elements.

Adding in the table:

$("#tableID").find('tbody')
    .append($('<tr>')
        .append($('<td>')
            .append($('<img>')
                .attr('src', 'img.png')
                .text('Image cell')
            )
        )
    );
  • The $('<some-tag>') in jQuery is a tag object that can have several attributes that can be set and get, text, which represents as the text between tag: <tag>text</tag>.

Solution 3:

  • Since jQuery version 1.4 automatically detects if the element we are trying to insert (using any of the append(), prepend(), before(), or after() methods) is a <tr> and inserts it into the first <tbody> in table or wraps it into a new <tbody>
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Solution 4:

Using <tbody> and a <tfoot>
Insert a row in the foot not in a body.

<table>
    <tbody>
        <tr><td>Foo</td></tr>
    </tbody>
    <tfoot>
        <tr><td>footer information</td></tr>
    </tfoot>
</table>
  • To include a <tbody> tag and use .append, rather than .after.
$("#myTable > tbody").append("<tr><td>row content</td></tr>");

Solution 5:

Try this:

$('#myTable > tbody:first').append('<tr>...</tr><tr>...</tr>'); 

Using this code:

$('#myTable > tbody:last').append('<tr>...</tr><tr>...</tr>'); 

The first and last keywords work on the first or last tag to be started, not closed. It is nested tables while we don't want the nested table to be changed, but instead add to the overall table

<table id=myTable>
  <tbody id=first>
    <tr><td>
      <table id=myNestedTable>
        <tbody id=last>
        </tbody>
      </table>
    </td></tr>
  </tbody>
</table>


Related Searches to Add table row in jQuery - javascript tutorial