Home » Javascript JQuery Examples » Remove last tr (row) from table – Javascript & jQuery

Remove last tr (row) from table – Javascript & jQuery

Deleting the last row <tr> from table- Example

Here’s an example code snippet that demonstrates how to remove the last <tr> (table row) element from a table using both JavaScript and jQuery:

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<table id="myTable">
  <tr>
    <td>Row 1, Cell 1</td>
    <td>Row 1, Cell 2</td>
  </tr>
  <tr>
    <td>Row 2, Cell 1</td>
    <td>Row 2, Cell 2</td>
  </tr>
  <tr>
    <td>Row 3, Cell 1</td>
    <td>Row 3, Cell 2</td>
  </tr>
</table>

<button id="removeRow">Remove Last Row</button>

<script>

// Using JavaScript

document.getElementById("removeRow").addEventListener("click", "function() { var table = document.getElementById("myTable"); var lastRow = table.rows[table.rows.length - 1]; if (lastRow) { table.deleteRow(table.rows.length - 1); } });

// Using jQuery

$("#removeRow").on("click", function() { $("#myTable tr:last").remove(); }); </script> </body> </html>

In this example, we have a table with some rows and a button. When the button is clicked, the last row of the table is removed using both JavaScript (document.getElementById and table.deleteRow) and jQuery ($(“#myTable tr:last”).remove()). Make sure to include the jQuery library by adding the <script> tag in the <head> section of your HTML file.