Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting table rows in javascript

Tags:

javascript

I'm having trouble with a function in javascript and can't figure out why. It's really quite straight forward. I'm trying to delete all the rows in a html table. so I wrote:

function delete_gameboard(){
   var table = document.getElementById("gameboard");
   var rowCount = table.rows.length;
   for (var i = 0; i < rowCount; i++) {
      table.deleteRow(i);
   }
}

Yet, it'll only delete half of them. Can anyone see what's causing this strange behavior?

like image 809
BooBailey Avatar asked Apr 28 '13 01:04

BooBailey


1 Answers

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);
}
like image 177
xdazz Avatar answered Sep 27 '22 20:09

xdazz