[thelist] DOM, removing rows fun

.jeff jeff at members.evolt.org
Mon Sep 30 19:19:00 CDT 2002


tom,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Tom Dell'Aringa
>
> I'm dynamically adding/removing rows in a table with
> the DOM. The function below checks to see if the
> checkbox in the particular row is checked - if it is,
> it whacks the row.
>
> The function works fine as far as removing the row.
> The problem is that once that happens, it throws the
> while loop off, because the number of rows has
> *changed* since I removed one.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

you have two options.

1) loop from the beginning to the end.  if a row is marked
   to be deleted, remove it, and decrement your counter

2) loop from the end to the beginning.  if a row is marked
   to be deleted, remove it.

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> while(x < numrows)
> {
>   if(!x == 0)
>   {
>     curID = table.getElementsByTagName("TR").item(x).id;
>     CBID = "cb_" + curID;
>     curCB = document.getElementById(CBID);
>
>     if(curCB.checked == true)
>     {
>       row = table.getElementsByTagName("TR").item(x);
>       tbody.removeChild(row);
>     }
>   }
>   x = x + 1;
> }
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

rather than doing a while loop, i'd recommend using a for loop which will make this block of code much easier to read.  additionally, if something is "not equal" to something else, use != and not !var == somevalue.  it's always easier to spot when the operators are all together.  lastly, if you're going to not do anything except increment if x equals 0, then why not just set x to 1 to begin with and lose that entire conditional statement that has to be evaluated each time through the loop?  that should noticeably increase the performance.

based on your two choices above, here's what i'd do:

1)

for(var x = 1; x < numrows; x++)
{
  curID = table.getElementsByTagName("TR").item(x).id;
  CBID = "cb_" + curID;
  curCB = document.getElementById(CBID);

  if(curCB.checked == true)
  {
    row = table.getElementsByTagName("TR").item(x);
    tbody.removeChild(row);
    x--;
  }
}

2)

for(var x = numrows - 1; x >= 1; x--)
{
  curID = table.getElementsByTagName("TR").item(x).id;
  CBID = "cb_" + curID;
  curCB = document.getElementById(CBID);

  if(curCB.checked == true)
  {
    row = table.getElementsByTagName("TR").item(x);
    tbody.removeChild(row);
  }
}

good luck,

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/




More information about the thelist mailing list