Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
With JavaScript DOM delete rows in a table?
To delete rows in a table in JavaScript, use the DOM deleteRow() method. This method removes a row from a table by specifying its index position.
Syntax
table.deleteRow(index)
Parameters
The index parameter specifies which row to delete (0-based indexing). Use -1 to delete the last row.
Example: Delete Rows One by One
The following example shows how to delete table rows. Each click removes the first row:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteFirstRow() {
var table = document.getElementById('newtable');
if (table.rows.length > 0) {
table.deleteRow(0);
} else {
alert('No more rows to delete!');
}
}
function deleteLastRow() {
var table = document.getElementById('newtable');
if (table.rows.length > 0) {
table.deleteRow(-1);
} else {
alert('No more rows to delete!');
}
}
</script>
</head>
<body>
<table style="border:2px solid black;" id="newtable">
<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>
<p>
<button onclick="deleteFirstRow()">Delete First Row</button>
<button onclick="deleteLastRow()">Delete Last Row</button>
</p>
</body>
</html>
Example: Delete Specific Row by Index
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRowByIndex() {
var table = document.getElementById('dataTable');
var index = document.getElementById('rowIndex').value;
if (index >= 0 && index < table.rows.length) {
table.deleteRow(index);
alert('Row ' + index + ' deleted!');
} else {
alert('Invalid row index!');
}
}
</script>
</head>
<body>
<table border="1" id="dataTable">
<tr><td>Index 0</td><td>Data A</td></tr>
<tr><td>Index 1</td><td>Data B</td></tr>
<tr><td>Index 2</td><td>Data C</td></tr>
<tr><td>Index 3</td><td>Data D</td></tr>
</table>
<p>
Enter row index: <input type="number" id="rowIndex" min="0" value="0">
<button onclick="deleteRowByIndex()">Delete Row</button>
</p>
</body>
</html>
Key Points
- Row indexing starts from 0
- Use index -1 to delete the last row
- Always check if rows exist before deleting to avoid errors
- The
table.rows.lengthproperty gives the total number of rows
Conclusion
The deleteRow() method provides a simple way to remove table rows dynamically. Always validate row indexes to prevent errors when deleting non-existent rows.
Advertisements
