≡ Menu
Deep in the Code

When JavaScript’s deleteRow() Method Doesn’t Work

A section of JavaScript code that uses the method deleteRow() was giving me a headache in IE 11. I did not encounter this when using Chrome.

In the code segment below, the variable “oHtmlTable” is assigned to an HTML table that already exists on a webpage.

//delete prior entries
while(oHtmlTable.rows.length > 1)					
{
	oHtmlTable.deleteRow(-1);
}

For no apparent reason, during the execution of the while loop, the deleteRow() method would quit working, but did not cause an exception to be thrown. Since the condition on the while loop would never be met if the rows in the table were no longer being deleted, this became an infinite loop.

IE gave no obvious indication as to what the problem was, just the standard “[domain name] is not responding” message at the bottom of the screen.

not responding

The code inside the while loop deletes the last row in the table. Whatever was inside the last row was keeping IE from successfully deleting it. First, I tried emptying the innerHTML contents of the last row to see if that would allow the deletion to continue. This had no effect. However, deleting the outerHTML contents of the row did the trick.

I created a variable in which to store the number of rows in the table, then an if statement to determine whether the row count changed after the deleteRow method was executed. If it was not, then on the next pass through the loop, the row would be deleted.

//delete prior entries
var nLength = 0;
while(oHtmlTable.rows.length > 1)					
{
	nLength = oHtmlTable.rows.length;
	oHtmlTable.deleteRow(-1);
	if (nLength == oHtmlTable.rows.length)
	{
		oHtmlTable.rows[nLength-1].outerHTML = '';
	}					
}