Adding rows to HTML table with jQuery

Adding rows to HTML table with jQuery When you have to dynamically add content to an HTML table in JavaScript, jQuery comes in handy. Although, it is not as simple as it could be expected. If you think there is a function like addRow(rowId, dataArray), I have to dispel the doubts, there is not. Nevertheless, a table can be updated in a few lines of code.

tableWhen you have to dynamically add content to an HTML table in JavaScript, jQuery comes in handy. Although, it is not as simple as it could be expected. If you think there is a function like addRow(rowId, dataArray), I have to dispel the doubts, there is not. Nevertheless, a table can be updated in a few lines of code.

 

 

Adding a row to an HTML table

At the beginning the table is build as below:

<table id="employeesTable">
<thead>
<tr>
<th>Id</th>
<th>Employee</th>
</tr>
</thead>
</table>

The table is identified by id - employeesTable and consists of two columns: Id and Employee. Each of them has a header defined in the thead tag. A new row can be added to it with the append jQuery function on the table DOM element.

$('#employeesTable').append("<tr><td>1</td><td>Thomas</td></tr>");

As you can see, tr and td tags has to be included. The append function just adds unstructured content to the table. Assuring a proper structure is developer's responsibility.

 

HTML table content reloading

The above example is very basic. What I think is really helpful is a piece of code that reloads the table from an array.

var reloadTable = function(employees) {
var table = $('#employeesTable');
table.find("tbody tr").remove();
employees.forEach(function (employee) {
table.append("<tr><td>" + employee.id + "</td><td>" + employee.name + "</td></tr>");
});
};

The employees table is an array of employee objects that have two fields: id and name. The first step of reloading is removing all data rows. An important part of it is choosing correct DOM elements (tbody tr) because I do not want to remove the column headers which are available on a different path (thead tr).

The second step is iterating through all array elements, building <tr> HTML code and appending it to table.