Deleting table rows in javascript
Consider this:
index 0: row #1
index 1: row #2
index 2: row #3
index 3: row #4
index 4: row #5
you delete index #2 (row #3), so the DOM engine adjusts the index keys and you end up with:
index 0: row #1
index 1: row #2
index 2: row #4 <---hey! index #2 is still there
index 3: row #5
You're basically digging a hole in the spot where you're standing, so as you dig deeper, you naturally sink deeper and never see any progress... until you run out of rows to delete in the table.
Because when you delete the first row, the second row will become the first, it's dynamic.
You could do like:
while(table.rows.length > 0) {
table.deleteRow(0);
}
function delete_gameboard(){
var table = document.getElementById("gameboard");
var rowCount = table.rows.length;
for (var i=rowcount-1; i >=0; i--) {
table.deleteRow(i);
}
}
The index of the row changes when you delete it. Use a reverse loop. This will also be helpful if you are using any condition to delete rows. If you are deleting all rows,use the following
while(table.rows.length) {
table.deleteRow(0);
}