How to Add a Row to a Table Using jQuery: A Complete Guide
Working with HTML tables is one of the most common tasks for a frontend developer. And dynamically adding new rows to a table is a classic of the genre. Imagine: you're building an online store, a blog admin panel, or a task management system. Almost always, you need the user to be able to click an "Add" button — and a new record appears in the table.
Today, we'll take a detailed look at how to add a table row in jQuery. This isn't just dry theory, but a practical step-by-step tutorial with live code examples. You'll learn about the most popular methods, pitfalls, and best practices. Let's go!
Why jQuery and not plain JavaScript?
A valid question. Yes, native JavaScript has been able to work with the DOM for a long time, and the document.createElement method hasn't been canceled. But jQuery teaches you to add a table row faster and easier, especially if you're a beginner. jQuery handles cross-browser compatibility and provides an elegant syntax. Plus, millions of lines of code in production are written in jQuery — and they need to be maintained. Therefore, knowing these techniques is a must-have skill for a web developer.
Basic HTML for Our Experiments
First, we need a simple table. Here's its markup — copy it into your HTML file or a sandbox like CodePen.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Add Row to Table jQuery</title> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script></head><body>
<h2>Employee List</h2><table id="employees" border="1"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Salary</th> </tr> </thead> <tbody> <tr> <td>Anna</td> <td>Developer</td> <td>150,000 ₽</td> </tr> <tr> <td>Ivan</td> <td>Designer</td> <td>120,000 ₽</td> </tr> </tbody></table>
<button id="addRow">Add Row</button>
<script>// Our jQuery code will go here</script>
</body></html>Notice: the table has a thead (header) and a tbody (body). This is the correct semantic structure. Adding a table row in jQuery will be done specifically in the tbody, not in the table itself — this way we won't break the headers.
Method #1: jQuery append — The Classic
The most popular way is to use the .append() method. It adds content to the end of the selected element. In our case — to the end of the tbody.
Let's say we want to add a new employee. The code would be:
$('#addRow').on('click', function() { var newRow = '<tr>' + '<td>Peter</td>' + '<td>Manager</td>' + '<td>100,000 ₽</td>' + '</tr>'; $('#employees tbody').append(newRow);});It's brilliantly simple: we build an HTML string with the new table row and insert it using the jQuery add table row method append. Now, every time the button is clicked, Peter the Manager appears in the table.
Important: if you don't have a tbody in your markup, jQuery might add the row directly to the table, but in that case, it might be inserted in the wrong place. Always use tbody!