Tips & Tricks: How to add a new Table Row using jQuery

In Dynamic websites we often find that we need to modify page content on the fly based on user actions. A common example of this is allowing the user to add additional input boxes for configurations or attachments. I personally like to contain such input as a new row in a table. To accomplish this I utilize the jQuery library for JavaScript.

For illustration lets assume we have the following table in our page:

RochesterNew York

In this example the approach to adding more columns is very straightforward as we can utilize jQuery’s child and last selectors with the after modifier to add a new table row.

var newRow = 'AlbanyNew York';
$('#exampleTable1 tr:last').after(newRow);

These 2 lines of JavaScript create the new row as a string then utilizes jQuery to get the last row of the table and append the new row after it, adding this row to the end of our table.

If a table contains a tfoot element with rows then the above will insert a row in the footer, A modification that can be done is to obtain the tbody element of the table and append the new row.

$('#exampleTable1 tbody').append(newRow);

That is all there is to it simply define your new row as a string then utilize jQuery to identify where you would like that row added to the DOM.

Comments & Questions

Add Your Comment