[thelist] DOM, removing rows fun [SOLVED]

Tom Dell'Aringa pixelmech at yahoo.com
Mon Sep 30 19:30:00 CDT 2002


--- ".jeff" <jeff at members.evolt.org> wrote:
> 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.

>
> 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);
>   }
> }

As Par Usual - jeff nailed it. Turns out option 1) actually doesn't
work, when it comes back around to

curID = table.getElementsByTagName("TR").item(x).id;

its gone (even with the decrement) so it throws an error, then I saw
option 2) and realized that in the for statement, it had the dynamism
of

var x = numrows - 1; x >= 1

which seems to adjust x correctly so no error is thrown.

Works perfect!

Thanks jeff and all who gave help.

Tom

=====
var me = tom.pixelmech.webDeveloper();

http://www.pixelmech.com/
http://www.maccaws.com/
[Making A Commercial Case for Adopting Web Standards]

__________________________________________________
Do you Yahoo!?
New DSL Internet Access from SBC & Yahoo!
http://sbc.yahoo.com



More information about the thelist mailing list