Delete all rows from table in javascript
for(var i = document.getElementById("tableId").rows.length; i > 0;i--)
{
document.getElementById("tableId").deleteRow(i -1);
}
I had to write this because it took me an hour to find out the error about deleting rows from an html table by javascript.
If you do this it generates an error :
for(var i = 0; i
serkan sendur
Postaholic
2,062 posts since Jan 2008
Reputation Points: 854
Solved Threads: 127
The easiest way to delete all rows from a table is this
var Parent = document.getElementById(tableID);
while(Parent.hasChildNodes())
{
Parent.removeChild(Parent.firstChild);
}
Note that when using removeChild that if it removes the last element it will also delete the parent node. I guess it assumes that if you have no child nodes then you don't need the parent node.
Also, don't make a habit of making function calls inside the loop, it is costly.
var Parent = document.getElementById(tableID);
while(Parent.hasChildNodes())
Is MUCH more preferable to
while(document.getElementById(tableID).hasChildNodes())
ShawnCplus
Code Monkey
1,583 posts since Apr 2005
Reputation Points: 526
Solved Threads: 268
If you still need it, this will delete all rows from your table, except for your head row.
var table = document.getElementById("tableid");
//or use : var table = document.all.tableid;
for(var i = table.rows.length - 1; i > 0; i--)
{
table.deleteRow(i);
}
Change the red "0" to "-1" if you wish to delete all rows, including the head row if you have one.
SheSaidImaPregy
Veteran Poster
1,080 posts since Sep 2007
Reputation Points: 43
Solved Threads: 68
The deleteRow(index) approach used here is much better than the ad hoc removeChild() approach IMO.
Here is my stab at it (untested)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv"Script-Content-Type" content="text/javascript">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Expires" content="0"> <!-- disable caching -->
<title>Example</title>
<script type="text/javascript">
function deleteRows(id, toDeleteHeader) {
var obj = document.getElementById(id);
if(!obj && !obj.rows)
return;
if(typeof toDeleteHeader == 'undefined')
toDeleteHeader = false;
var limit = !!toDeleteHeader ? 0 : 1;
var rows = obj.rows;
if(limit > rows.length)
return;
for(; rows.length > limit; ) {
obj.deleteRow(limit);
}
}
</script>
</head>
<body>
<table id="tbl" name="tbl" border="1">
<thead>
<tr>
<td>No.</td>
<td>Content</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Something</td>
</tr>
<tr>
<td>1</td>
<td>Something</td>
</tr>
<tr>
<td>1</td>
<td>Something</td>
</tr>
<tr>
<td>1</td>
<td>Something</td>
</tr>
</tbody>
</table>
<a href="#" onclick="deleteRows('tbl', false);">Delete rows</a>
</body>
</html>
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734