Dynamically adding rows to HTML tables is a frequent requirement in web development, particularly when building interactive user interfaces. This tutorial demonstrates efficient methods for achieving this using both jQuery and plain JavaScript, allowing you to choose the approach best suited to your project.
Table of Contents
Adding Table Rows with jQuery’s append()
and prepend()
jQuery offers a concise and efficient way to manipulate the DOM. Its append()
and prepend()
methods seamlessly integrate with table structures.
Let’s consider a sample HTML table:
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<tr>
</thead>
<tbody>
<!-- Rows will be added here -->
</tbody>
</table>
To add a new row using jQuery:
// Get the table body
let $tableBody = $('#myTable tbody');
// Create the new row
let $newRow = $('<tr>');
// Create and append cells
$newRow.append('<td>New Name</td>');
$newRow.append('<td>30</td>');
// Append the row to the table body
$tableBody.append($newRow);
This code snippet selects the table body, creates a new row element, adds data cells, and appends the complete row to the table. For prepending (adding to the beginning), simply use $tableBody.prepend($newRow);
.
For more complex scenarios or adding multiple rows, building the row HTML string directly can be more efficient:
let newRowHTML = `<tr><td>Another Name</td><td>25</td></tr>`;
$tableBody.append(newRowHTML);
Remember to sanitize user-supplied data to prevent XSS vulnerabilities.
Adding Table Rows with Plain JavaScript
Understanding the native JavaScript approach provides a deeper understanding of DOM manipulation. While more verbose, it avoids external dependencies.
let tableBody = document.getElementById('myTable').querySelector('tbody');
let newRow = document.createElement('tr');
let nameCell = document.createElement('td');
let ageCell = document.createElement('td');
nameCell.textContent = 'Yet Another Name';
ageCell.textContent = '40';
newRow.appendChild(nameCell);
newRow.appendChild(ageCell);
tableBody.appendChild(newRow);
This code directly manipulates the DOM using standard JavaScript methods. Choose the method that best suits your project’s needs and your comfort level with jQuery. Remember to include the jQuery library if using the jQuery examples: <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>