To dynamically append a new row to an HTML table using jQuery, build the <tr> and <td> elements with jQuery ($("<tr>") and $("<td>")) and attach them to the table’s <tbody> using .append(). Constructing elements via jQuery methods rather than concatenating raw HTML strings automatically escapes text values and prevents XSS injection when inserting dynamic or user-supplied data.
1. Building and Appending a Row Safely with jQuery
Create the <tr> and <td> nodes cleanly, set cell text with .text(), and append the completed row to tbody:
// Safely append a new row to a table's <tbody> using jQuery DOM construction
function appendTableRow(tableSelector, rowData) {
const $tbody = $(tableSelector).find("tbody");
const $row = $("<tr>");
$("<td>").text(rowData.name).appendTo($row);
$("<td>").text(rowData.role).appendTo($row);
$("<td>").text(rowData.status).appendTo($row);
$tbody.append($row);
return $row;
}
const newMemberRow = appendTableRow("#team-table", {
name: "Zainab Tariq",
role: "Frontend Engineer",
status: "Active"
});
console.log("Appended row count:", $("#team-table tbody tr").length, newMemberRow.length);
- Target
<tbody>explicitly: Appending to$(tableSelector).find("tbody")keeps rows grouped inside the body section rather than creating stray<tbody>blocks or affecting<thead>/<tfoot>. - Use
.text()for dynamic data: Sets cell text safely without interpreting HTML tags insiderowData. - Chainable reference: Returning
makes it easy to highlight, animate, or attach event listeners to the newly added row.
2. Adding Action Buttons or Event Handlers to Appended Rows
When a dynamically appended row needs interactive controls (such as a remove or toggle button), bind events via event delegation on a static parent or attach handlers directly to the created element:
// Append a row with a delete button and handle clicks via event delegation
function appendItemRowWithDelete(tableSelector, item) {
const $tbody = $(tableSelector).find("tbody");
const $row = $("<tr>").attr("data-item-id", item.id);
$("<td>").text(item.name).appendTo($row);
$("<td>").text(item.price).appendTo($row);
const $deleteBtn = $("<button>")
.attr("type", "button")
.addClass("remove-row-btn")
.text("Remove");
$("<td>").append($deleteBtn).appendTo($row);
$tbody.append($row);
}
// Delegated listener handles rows appended now or later
$("#items-table").on("click", ".remove-row-btn", function () {
$(this).closest("tr").remove();
});
appendItemRowWithDelete("#items-table", { id: 101, name: "Mechanical Keyboard", price: "$85.00" });
- Event delegation (
$(table).on("click", ".remove-row-btn", ...)): Works automatically for both initial rows and rows appended later without re-binding handlers. $(this).closest("tr").remove(): Cleanly locates and removes the exact row containing the clicked button.
3. Common Traps to Avoid
Dynamically adding table rows in jQuery runs into a few frequent snags:
- Interpolating untrusted strings into raw HTML strings (
$("<tr><td>" + userInput + "</td></tr>")): Allows injected HTML/scripts ifuserInputcontains markup—prefer$("<td>").text(value). - Appending directly to
<table>when multiple<tbody>elements exist: Targeting$(tableSelector).find("tbody").first()or a specifictbodyID avoids ambiguity when a table has multiple row groups. - Attaching direct
.click()handlers only on page load: Direct.click()bindings on existing buttons do not automatically cover rows added later unless delegated or bound on creation.
TL;DR: Construct $("<tr>") and $("<td>").text(...) in jQuery and append them to $(tableSelector).find("tbody") using .append(), using event delegation for actions inside dynamic rows.
Are you appending rows from form inputs, rendering data from an AJAX/JSON response, or adding interactive buttons/inputs inside each row?
