Forum Moderators: open

Message Too Old, No Replies

removing Rows in a loop

remove all rows in a single click

         

kadnan

7:39 am on Oct 8, 2005 (gmt 0)

10+ Year Member



i ve two buttns one to add a single row and other to remove all added rows

what actually happening that its leaving ONE Row everytime

i am doing following

var mytable=document.getElementById('divTableStatus1');
myr=mytable.getElementsByTagName('tr');

for(var u=0;u <= myr.length;u++)
{

document.getElementById('divTableStatus1').deleteRow(u)
}

Every time its leaving one row behind.

i also tried to implmenet bernard max`s following script for multiple row deletion,but no Luck

[webmasterworld.com...]

Help me please

Bernard Marx

2:07 pm on Oct 8, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A quick demo.

Remember that the node list of rows that you are referencing is live
- whether via

[blue]table.rows[/blue]
or
[blue]table.getElementsByTagName('tr')[/blue]
;

The

[blue]length[/blue]
will continue to update. This will confuse your algorithm if you had expected the
[blue]length[/blue]
not to change. You can either (a) save the initial length in a variable outside the loop, or (b) use the length to tell the loop when to stop - as in the below.


<html><head><title>TEST</title>
<script type="text/javascript">
function testFn()
{
var table = document.getElementById('test');
var rows = table.rows;
while(rows.length) [green]// length=0 -> stop[/green]
table.deleteRow(rows.length-1);
}
</script>
</head>
<body>
<table id="test" border="1">
<tr><td>A</td><td>B1</td></tr>
<tr><td>A</td><td>B2</td></tr>
<tr><td>A</td><td>B3</td></tr>
<tr><td>A</td><td>B4</td></tr>
</table>
<button onclick="testFn()">testFn()</button>
</body>
</html>

I have a feeling that removing child elements is quicker done bottom-up, so the function does that.

kadnan

5:44 am on Oct 11, 2005 (gmt 0)

10+ Year Member



Thanks a Lot!

-adnan