Add table row in jQuery

JavascriptJqueryHtml Table

Javascript Problem Overview


What is the best method in jQuery to add an additional row to a table as the last row?

Is this acceptable?

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)?

Javascript Solutions


Solution 1 - Javascript

The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody for example:

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

You would end up with the following:

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

I would therefore recommend this approach instead:

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

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

Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody unless you have specified one yourself.

DaRKoN_ suggests appending to the tbody rather than adding content after the last tr. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody elements and the row would get added to each of them.

Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.

I think the safest solution is probably to ensure your table always includes at least one tbody in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody elements):

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

Solution 2 - Javascript

jQuery has a built-in facility to manipulate DOM elements on the fly.

You can add anything to your table like this:

$("#tableID").find('tbody')
    .append($('<tr>')
        .append($('<td>')
            .append($('<img>')
                .attr('src', 'img.png')
                .text('Image cell')
            )
        )
    );

The $('<some-tag>') thing in jQuery is a tag object that can have several attr attributes that can be set and get, as well as text, which represents the text between the tag here: <tag>text</tag>.

This is some pretty weird indenting, but it's easier for you to see what's going on in this example.

Solution 3 - Javascript

So things have changed ever since @Luke Bennett answered this question. Here is an update.

jQuery since version 1.4(?) automatically detects if the element you 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 your table or wraps it into a new <tbody> if one doesn't exist.

So yes your example code is acceptable and will work fine with jQuery 1.4+. ;)

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Solution 4 - Javascript

What if you had a <tbody> and a <tfoot>?

Such as:

<table>
    <tbody>
        <tr><td>Foo</td></tr>
    </tbody>
    <tfoot>
        <tr><td>footer information</td></tr>
    </tfoot>
</table>

Then it would insert your new row in the footer - not to the body.

Hence the best solution is to include a <tbody> tag and use .append, rather than .after.

$("#myTable > tbody").append("<tr><td>row content</td></tr>");

Solution 5 - Javascript

I know you have asked for a jQuery method. I looked a lot and find that we can do it in a better way than using JavaScript directly by the following function.

tableObject.insertRow(index)

index is an integer that specifies the position of the row to insert (starts at 0). The value of -1 can also be used; which result in that the new row will be inserted at the last position.

This parameter is required in Firefox and Opera, but it is optional in Internet Explorer, Chrome and Safari.

If this parameter is omitted, insertRow() inserts a new row at the last position in Internet Explorer and at the first position in Chrome and Safari.

It will work for every acceptable structure of HTML table.

The following example will insert a row in last (-1 is used as index):

<html>
    <head>
        <script type="text/javascript">
        function displayResult()
        {
            document.getElementById("myTable").insertRow(-1).innerHTML = '<td>1</td><td>2</td>';
        }
        </script>
    </head>

    <body>       
        <table id="myTable" border="1">
            <tr>
                <td>cell 1</td>
                <td>cell 2</td>
            </tr>
            <tr>
                <td>cell 3</td>
                <td>cell 4</td>
            </tr>
        </table>
        <br />
        <button type="button" onclick="displayResult()">Insert new row</button>            
    </body>
</html>

I hope it helps.

Solution 6 - Javascript

I recommend

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

as opposed to

$('#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. Therefore, this plays nicer with nested tables, if you don't want the nested table to be changed, but instead add to the overall table. At least, this is what I found.

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

Solution 7 - Javascript

In my opinion the fastest and clear way is

//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');

//Then if no tbody just select your table 
var table = tbody.length ? tbody : $('#myTable');

//Add row
table.append('<tr><td>hello></td></tr>');

here is demo Fiddle

Also I can recommend a small function to make more html changes

//Compose template string
String.prototype.compose = (function (){
var re = /\{{(.+?)\}}/g;
return function (o){
        return this.replace(re, function (_, k){
            return typeof o[k] != 'undefined' ? o[k] : '';
        });
    }
}());

If you use my string composer you can do this like

var tbody = $('#myTable').children('tbody');
var table = tbody.length ? tbody : $('#myTable');
var row = '<tr>'+
    '<td>{{id}}</td>'+
    '<td>{{name}}</td>'+
    '<td>{{phone}}</td>'+
'</tr>';


//Add row
table.append(row.compose({
    'id': 3,
    'name': 'Lee',
    'phone': '123 456 789'
}));

Here is demo Fiddle

Solution 8 - Javascript

This can be done easily using the "last()" function of jQuery.

$("#tableId").last().append("<tr><td>New row</td></tr>");

Solution 9 - Javascript

I solved it this way.

Using jquery

$('#tab').append($('<tr>')
	.append($('<td>').append("text1"))
    .append($('<td>').append("text2"))
    .append($('<td>').append("text3"))
    .append($('<td>').append("text4"))
  )

Snippet

$('#tab').append($('<tr>')
  .append($('<td>').append("text1"))
  .append($('<td>').append("text2"))
  .append($('<td>').append("text3"))
  .append($('<td>').append("text4"))
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="tab">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
    <th>City</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
    <td>New York</td>
  </tr>
</table>

Solution 10 - Javascript

I'm using this way when there is not any row in the table, as well as, each row is quite complicated.

style.css:

...
#templateRow {
  display:none;
}
...

xxx.html

...
<tr id="templateRow"> ... </tr>
...

$("#templateRow").clone().removeAttr("id").appendTo( $("#templateRow").parent() );

...

Solution 11 - Javascript

For the best solution posted here, if there's a nested table on the last row, the new row will be added to the nested table instead of the main table. A quick solution (considering tables with/without tbody and tables with nested tables):

function add_new_row(table, rowcontent) {
    if ($(table).length > 0) {
        if ($(table + ' > tbody').length == 0) $(table).append('<tbody />');
        ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent);
    }
}

Usage example:

add_new_row('#myTable','<tr><td>my new row</td></tr>');

Solution 12 - Javascript

I was having some related issues, trying to insert a table row after the clicked row. All is fine except the .after() call does not work for the last row.

$('#traffic tbody').find('tr.trafficBody).filter(':nth-child(' + (column + 1) + ')').after(insertedhtml);

I landed up with a very untidy solution:

create the table as follows (id for each row):

<tr id="row1"> ... </tr>
<tr id="row2"> ... </tr>
<tr id="row3"> ... </tr>

etc ...

and then :

$('#traffic tbody').find('tr.trafficBody' + idx).after(html);

Solution 13 - Javascript

You can use this great jQuery add table row function. It works great with tables that have <tbody> and that don't. Also it takes into the consideration the colspan of your last table row.

Here is an example usage:

// One table
addTableRow($('#myTable'));
// add table row to number of tables
addTableRow($('.myTables'));

Solution 14 - Javascript

    // Create a row and append to table
    var row = $('<tr />', {})
		.appendTo("#table_id");

    // Add columns to the row. <td> properties can be given in the JSON
	$('<td />', {
		'text': 'column1'
	}).appendTo(row);

	$('<td />', {
		'text': 'column2',
        'style': 'min-width:100px;'
	}).appendTo(row);

Solution 15 - Javascript

My solution:

//Adds a new table row
$.fn.addNewRow = function (rowId) {
    $(this).find('tbody').append('<tr id="' + rowId + '"> </tr>');
};

usage:

$('#Table').addNewRow(id1);

Solution 16 - Javascript

I found this AddRow plugin quite useful for managing table rows. Though, Luke's solution would be the best fit if you just need to add a new row.

Solution 17 - Javascript

Neil's answer is by far the best one. However things get messy really fast. My suggestion would be to use variables to store elements and append them to the DOM hierarchy.

HTML

<table id="tableID">
    <tbody>
    </tbody>
</table>

JAVASCRIPT

// Reference to the table body
var body = $("#tableID").find('tbody');

// Create a new row element
var row = $('<tr>');

// Create a new column element
var column = $('<td>');

// Create a new image element
var image = $('<img>');
image.attr('src', 'img.png');
image.text('Image cell');

// Append the image to the column element
column.append(image);
// Append the column to the row element
row.append(column);
// Append the row to the table body
body.append(row);

Solution 18 - Javascript

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

Write with a javascript function

document.getElementById("myTable").insertRow(-1).innerHTML = '<tr>...</tr><tr>...</tr>';

Solution 19 - Javascript

This is my solution

$('#myTable').append('<tr><td>'+data+'</td><td>'+other data+'</td>...</tr>');

Solution 20 - Javascript

Here is some hacketi hack code. I wanted to maintain a row template in an HTML page. Table rows 0...n are rendered at request time, and this example has one hardcoded row and a simplified template row. The template table is hidden, and the row tag must be within a valid table or browsers may drop it from the DOM tree. Adding a row uses counter+1 identifier, and the current value is maintained in the data attribute. It guarantees each row gets unique URL parameters.

I have run tests on Internet Explorer 8, Internet Explorer 9, Firefox, Chrome, Opera, Nokia Lumia 800, Nokia C7 (with Symbian 3), Android stock and Firefox beta browsers.

<table id="properties">
<tbody>
  <tr>
    <th>Name</th>
    <th>Value</th>
    <th>&nbsp;</th>
  </tr>
  <tr>
    <td nowrap>key1</td>
    <td><input type="text" name="property_key1" value="value1" size="70"/></td>
    <td class="data_item_options">
       <a class="buttonicon" href="javascript:deleteRow()" title="Delete row" onClick="deleteRow(this); return false;"></a>
    </td>
  </tr>
</tbody>
</table>

<table id="properties_rowtemplate" style="display:none" data-counter="0">
<tr>
 <td><input type="text" name="newproperty_name_\${counter}" value="" size="35"/></td>
 <td><input type="text" name="newproperty_value_\${counter}" value="" size="70"/></td>
 <td><a class="buttonicon" href="javascript:deleteRow()" title="Delete row" onClick="deleteRow(this); return false;"></a></td>
</tr>
</table>
<a class="action" href="javascript:addRow()" onclick="addRow('properties'); return false" title="Add new row">Add row</a><br/>
<br/>

- - - - 
// add row to html table, read html from row template
function addRow(sTableId) {
	// find destination and template tables, find first <tr>
	// in template. Wrap inner html around <tr> tags.
	// Keep track of counter to give unique field names.
	var table  = $("#"+sTableId);
	var template = $("#"+sTableId+"_rowtemplate");
	var htmlCode = "<tr>"+template.find("tr:first").html()+"</tr>";
	var id = parseInt(template.data("counter"),10)+1;
	template.data("counter", id);
	htmlCode = htmlCode.replace(/\${counter}/g, id);
	table.find("tbody:last").append(htmlCode);
}

// delete <TR> row, childElem is any element inside row
function deleteRow(childElem) {
	var row = $(childElem).closest("tr"); // find <tr> parent
	row.remove();
}

PS: I give all credits to the jQuery team; they deserve everything. JavaScript programming without jQuery - I don't even want think about that nightmare.

Solution 21 - Javascript

<tr id="tablerow"></tr>

$('#tablerow').append('<tr>...</tr><tr>...</tr>');

Solution 22 - Javascript

I Guess i have done in my project , here it is:

html

<div class="container">
    <div class = "row">
    <div class = "span9">
        <div class = "well">
          <%= form_for (@replication) do |f| %>
    <table>
    <tr>
      <td>
          <%= f.label :SR_NO %>
      </td>
      <td>
          <%= f.text_field :sr_no , :id => "txt_RegionName" %>
      </td>
    </tr>
    <tr>
      <td>
        <%= f.label :Particular %>
      </td>
      <td>
        <%= f.text_area :particular , :id => "txt_Region" %>
      </td>
    </tr>
    <tr>
      <td>
        <%= f.label :Unit %>
      </td>
      <td>
        <%= f.text_field :unit ,:id => "txt_Regio" %>
      </td>
      </tr>
      <tr>

      <td> 
        <%= f.label :Required_Quantity %>
      </td>
      <td>
        <%= f.text_field :quantity ,:id => "txt_Regi" %>
      </td>
    </tr>
    <tr>
    <td></td>
    <td>
    <table>
    <tr><td>
    <input type="button"  name="add" id="btn_AddToList" value="add" class="btn btn-primary" />
    </td><td><input type="button"  name="Done" id="btn_AddToList1" value="Done" class="btn btn-success" />
    </td></tr>
    </table>
    </td>
    </tr>
    </table>
    <% end %>
    <table id="lst_Regions" style="width: 500px;" border= "2" class="table table-striped table-bordered table-condensed">
    <tr>
    <td>SR_NO</td>
    <td>Item Name</td>
    <td>Particular</td>
    <td>Cost</td>
    </tr>
    </table>
    <input type="button" id= "submit" value="Submit Repication"  class="btn btn-success" />
    </div>
    </div>
    </div>
</div>

js

$(document).ready(function() {     
    $('#submit').prop('disabled', true);
    $('#btn_AddToList').click(function () {
     $('#submit').prop('disabled', true);
    var val = $('#txt_RegionName').val();
    var val2 = $('#txt_Region').val();
    var val3 = $('#txt_Regio').val();
    var val4 = $('#txt_Regi').val();
    $('#lst_Regions').append('<tr><td>' + val + '</td>' + '<td>' + val2 + '</td>' + '<td>' + val3 + '</td>' + '<td>' + val4 + '</td></tr>');
    $('#txt_RegionName').val('').focus();
    $('#txt_Region').val('');
        $('#txt_Regio').val('');
        $('#txt_Regi').val('');
    $('#btn_AddToList1').click(function () {
         $('#submit').prop('disabled', false).addclass('btn btn-warning');
    });
      });
});

Solution 23 - Javascript

if you have another variable you can access in <td> tag like that try.

This way I hope it would be helpful

var table = $('#yourTableId');
var text  = 'My Data in td';
var image = 'your/image.jpg'; 
var tr = (
  '<tr>' +
    '<td>'+ text +'</td>'+
    '<td>'+ text +'</td>'+
    '<td>'+
      '<img src="' + image + '" alt="yourImage">'+
    '</td>'+
  '</tr>'
);

$('#yourTableId').append(tr);

Solution 24 - Javascript

<table id=myTable>
	<tr><td></td></tr>
	<style="height=0px;" tfoot></tfoot>
</table>

You can cache the footer variable and reduce access to DOM (Note: may be it will be better to use a fake row instead of footer).

var footer = $("#mytable tfoot")
footer.before("<tr><td></td></tr>")

Solution 25 - Javascript

As i have also got a way too add row at last or any specific place so i think i should also share this:

First find out the length or rows:

var r=$("#content_table").length;

and then use below code to add your row:

$("#table_id").eq(r-1).after(row_html);

Solution 26 - Javascript

To add a good example on the topic, here is working solution if you need to add a row at specific position.

The extra row is added after the 5th row, or at the end of the table if there are less then 5 rows.

var ninja_row = $('#banner_holder').find('tr');
	 
if( $('#my_table tbody tr').length > 5){
	$('#my_table tbody tr').filter(':nth-child(5)').after(ninja_row);
}else{
	$('#my_table tr:last').after(ninja_row);
}

I put the content on a ready (hidden) container below the table ..so if you(or the designer) have to change it is not required to edit the JS.

<table id="banner_holder" style="display:none;"> 
	<tr>
		<td colspan="3">
			<div class="wide-banner"></div>
		</td>	
	</tr> 
</table>

Solution 27 - Javascript

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

will add a new row to the first TBODY of the table, without depending of any THEAD or TFOOT present. (I didn't find information from which version of jQuery .append() this behavior is present.)

You may try it in these examples:

<table class="t"> <!-- table with THEAD, TBODY and TFOOT -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t"> <!-- table with two TBODYs -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tbody>
  <tr><td>3</td><td>4</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t">  <!-- table without TBODY -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
</table><br>

<table class="t">  <!-- table with TR not in TBODY  -->
  <tr><td>1</td><td>2</td></tr>
</table>
<br>
<table class="t">
</table>

<script>
$('.t').append('<tr><td>a</td><td>a</td></tr>');
</script>

In which example a b row is inserted after 1 2, not after 3 4 in second example. If the table were empty, jQuery creates TBODY for a new row.

Solution 28 - Javascript

If you are using Datatable JQuery plugin you can try.

oTable = $('#tblStateFeesSetup').dataTable({
            "bScrollCollapse": true,
            "bJQueryUI": true,
			...
			...
			//Custom Initializations.
			});

//Data Row Template of the table.
var dataRowTemplate = {};
dataRowTemplate.InvoiceID = '';
dataRowTemplate.InvoiceDate = '';
dataRowTemplate.IsOverRide = false;
dataRowTemplate.AmountOfInvoice = '';
dataRowTemplate.DateReceived = '';
dataRowTemplate.AmountReceived = '';
dataRowTemplate.CheckNumber = '';

//Add dataRow to the table.
oTable.fnAddData(dataRowTemplate);

Refer Datatables fnAddData Datatables API

Solution 29 - Javascript

In a simple way:

$('#yourTableId').append('<tr><td>your data1</td><td>your data2</td><td>your data3</td></tr>');

Solution 30 - Javascript

Try this : very simple way

$('<tr><td>3</td></tr><tr><td>4</td></tr>').appendTo("#myTable tbody");

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="myTable">
  <tbody>
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
  </tbody>
</table>

Solution 31 - Javascript

The answers above are very helpful, but when student refer this link to add data from form they often require a sample.

I want to contribute an sample get input from from and use .after() to insert tr to table using string interpolation.

function add(){
  let studentname = $("input[name='studentname']").val();
  let studentmark = $("input[name='studentmark']").val();

  $('#student tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);
}

function add(){
let studentname = $("input[name='studentname']").val();
let studentmark = $("input[name='studentmark']").val();

$('#student tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>
<form>
<input type='text' name='studentname' />
<input type='text' name='studentmark' />
<input type='button' onclick="add()" value="Add new" />
</form>
<table id='student'>
  <thead>
    <th>Name</th>
    <th>Mark</th>
  </thead>
</table>
</body>
</html>

Solution 32 - Javascript

If you want to add row before the <tr> first child.

$("#myTable > tbody").prepend("<tr><td>my data</td><td>more data</td></tr>");

If you want to add row after the <tr> last child.

$("#myTable > tbody").append("<tr><td>my data</td><td>more data</td></tr>");

Solution 33 - Javascript

)Daryl:

You can append it to the tbody using the appendTo method like this:

$(() => {
   $("<tr><td>my data</td><td>more data</td></tr>").appendTo("tbody");
});

You'll probably want to use the latest JQuery and ECMAScript. Then you can use a back-end language to add your data to the table. You can also wrap it in a variable like so:

$(() => {
  var t_data = $('<tr><td>my data</td><td>more data</td></tr>');
  t_data.appendTo('tbody');
});

Solution 34 - Javascript

Add tabe row using JQuery:

if you want to add row after last of table's row child, you can try this

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

if you want to add row 1st of table's row child, you can try this

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

Solution 35 - Javascript

Pure JS is quite short in your case

myTable.firstChild.innerHTML += '<tr><td>my data</td><td>more data</td></tr>'

function add() {
  myTable.firstChild.innerHTML+=`<tr><td>date</td><td>${+new Date}</td></tr>`
}

td {border: 1px solid black;}

<button onclick="add()">Add</button><br>
<table id="myTable"><tbody></tbody> </table>

(if we remove <tbody> and firstChild it will also works but wrap every row with <tbody>)

Solution 36 - Javascript

I have tried the most upvoted one, but it did not work for me, but below works well.

$('#mytable tr').last().after('<tr><td></td></tr>');

Which will work even there is a tobdy there.

Solution 37 - Javascript

  1. Using jQuery .append()
  2. Using jQuery .appendTo()
  3. Using jQuery .after()
  4. Using Javascript .insertRow()
  5. Using jQuery - add html row

Try This:

// Using jQuery - append
$('#myTable > tbody').append('<tr><td>3</td><td>Smith Patel</td></tr>');

// Using jQuery - appendTo
$('<tr><td>4</td><td>J. Thomson</td></tr>').appendTo("#myTable > tbody");

// Using jQuery - add html row
let tBodyHtml = $('#myTable > tbody').html();
tBodyHtml += '<tr><td>5</td><td>Patel S.</td></tr>';
$('#myTable > tbody').html(tBodyHtml);

// Using jQuery - after
$('#myTable > tbody tr:last').after('<tr><td>6</td><td>Angel Bruice</td></tr>');

// Using JavaScript - insertRow
const tableBody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
const newRow = tableBody.insertRow(tableBody.rows.length);
newRow.innerHTML = '<tr><td>7</td><td>K. Ashwin</td></tr>';

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>John Smith</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Tom Adam</td>
        </tr>
    </tbody>
</table>

Solution 38 - Javascript

This could also be done :

$("#myTable > tbody").html($("#myTable > tbody").html()+"<tr><td>my data</td><td>more data</td></tr>")

Solution 39 - Javascript

To add a new row at the last of current row, you can use like this

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

You can append multiple row as above. Also you can add inner data as like

$('#yourtableid tr:last').after('<tr><td>your data</td></tr>');

in another way you can do like this

let table = document.getElementById("tableId");

let row = table.insertRow(1); // pass position where you want to add a new row


//then add cells as you want with index
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
let cell3 = row.insertCell(3);


//add value to added td cell
 cell0.innerHTML = "your td content here";
 cell1.innerHTML = "your td content here";
 cell2.innerHTML = "your td content here";
 cell3.innerHTML = "your td content here";

Solution 40 - Javascript

Here, You can Just Click on button then you will get Output. When You Click on Add row button then one more row Added.

I hope It is very helpful.

<html> 

<head> 
	<script src= 
			"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
	</script> 
	
	<style> 
		table { 
			margin: 25px 0; 
			width: 200px; 
		} 

		table th, table td { 
			padding: 10px; 
			text-align: center; 
		} 

		table, th, td { 
			border: 1px solid; 
		} 
	</style> 
</head> 

<body> 
	
	<b>Add table row in jQuery</b> 
	
	<p> 
		Click on the button below to 
		add a row to the table 
	</p> 
	
	<button class="add-row"> 
		Add row 
	</button> 
	
	<table> 
		<thead> 
			<tr> 
				<th>Rows</th> 
			</tr> 
		</thead> 
		<tbody> 
			<tr> 
				<td>This is row 0</td> 
			</tr> 
		</tbody> 
	</table> 
	
	<!-- Script to add table row -->
	<script> 
		let rowno = 1; 
		$(document).ready(function () { 
			$(".add-row").click(function () { 
				rows = "<tr><td>This is row " 
					+ rowno + "</td></tr>"; 
				tableBody = $("table tbody"); 
				tableBody.append(rows); 
				rowno++; 
			}); 
		}); 
	</script> 
</body> 
</html>					 

Solution 41 - Javascript

var html = $('#myTableBody').html();
html += '<tr><td>my data</td><td>more data</td></tr>';
$('#myTableBody').html(html);

or

$('#myTableBody').html($('#myTableBody').html() + '<tr><td>my data</td><td>more data</td></tr>');

Solution 42 - Javascript

TIP: Inserting rows in html table via innerHTML or .html() is not valid in some browsers (similar IE9), and using .append("<tr></tr>") is not good suggestion in any browser. best and fastest way is using the pure javascript codes.

for combine this way with jQuery, only add new plugin similar this to jQuery:

$.fn.addRow=function(index/*-1: add to end  or  any desired index*/, cellsCount/*optional*/){
    if(this[0].tagName.toLowerCase()!="table") return null;
	var i=0, c, r = this[0].insertRow((index<0||index>this[0].rows.length)?this[0].rows.length:index);
    for(;i<cellsCount||0;i++) c = r.insertCell(); //you can use c for set its content or etc
    return $(r);
};

And now use it in whole the project similar this:

var addedRow = $("#myTable").addRow(-1/*add to end*/, 2);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarryl HeinView Question on Stackoverflow
Solution 1 - JavascriptLuke BennettView Answer on Stackoverflow
Solution 2 - JavascriptNeilView Answer on Stackoverflow
Solution 3 - JavascriptSalman von AbbasView Answer on Stackoverflow
Solution 4 - JavascriptChadTView Answer on Stackoverflow
Solution 5 - JavascriptshashwatView Answer on Stackoverflow
Solution 6 - JavascriptCurtorView Answer on Stackoverflow
Solution 7 - JavascriptsulestView Answer on Stackoverflow
Solution 8 - JavascriptNischalView Answer on Stackoverflow
Solution 9 - JavascriptAnton vBRView Answer on Stackoverflow
Solution 10 - JavascriptDominicView Answer on Stackoverflow
Solution 11 - JavascriptOshuaView Answer on Stackoverflow
Solution 12 - JavascriptAvron OlshewskyView Answer on Stackoverflow
Solution 13 - JavascriptUzbekjonView Answer on Stackoverflow
Solution 14 - JavascriptPankaj GargView Answer on Stackoverflow
Solution 15 - JavascriptRicky GView Answer on Stackoverflow
Solution 16 - JavascriptVitalii FedorenkoView Answer on Stackoverflow
Solution 17 - JavascriptGabrielOshiroView Answer on Stackoverflow
Solution 18 - JavascriptJakir HossainView Answer on Stackoverflow
Solution 19 - JavascriptDaniel OrtegónView Answer on Stackoverflow
Solution 20 - JavascriptWhomeView Answer on Stackoverflow
Solution 21 - JavascriptVivek SView Answer on Stackoverflow
Solution 22 - JavascriptSNEH PANDYAView Answer on Stackoverflow
Solution 23 - JavascriptMEAbidView Answer on Stackoverflow
Solution 24 - JavascriptPavel ShkleinikView Answer on Stackoverflow
Solution 25 - JavascriptJaid07View Answer on Stackoverflow
Solution 26 - Javascriptd.raevView Answer on Stackoverflow
Solution 27 - JavascriptAlexey PavlovView Answer on Stackoverflow
Solution 28 - JavascriptPraveena MView Answer on Stackoverflow
Solution 29 - Javascriptvipul sorathiyaView Answer on Stackoverflow
Solution 30 - JavascriptrajmobiappView Answer on Stackoverflow
Solution 31 - JavascriptHien NguyenView Answer on Stackoverflow
Solution 32 - JavascriptSumon SarkerView Answer on Stackoverflow
Solution 33 - JavascriptMarkView Answer on Stackoverflow
Solution 34 - JavascriptRizwanView Answer on Stackoverflow
Solution 35 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 36 - JavascriptRinto GeorgeView Answer on Stackoverflow
Solution 37 - JavascriptSahil ThummarView Answer on Stackoverflow
Solution 38 - JavascriptPrashantView Answer on Stackoverflow
Solution 39 - JavascriptHemant N. KarmurView Answer on Stackoverflow
Solution 40 - JavascriptNikhil BView Answer on Stackoverflow
Solution 41 - Javascriptmostafa tolooView Answer on Stackoverflow
Solution 42 - JavascriptHassan SadeghiView Answer on Stackoverflow