RE: An observation about "live" NodeLists

Mike Champion wrote,
> Bein' kinda stupid mahself, I'd prob'ly code this:
> 
> 
>    NodeList nl = aDocument.getElementsByTagName("p");
>    int i = 0;
>    Node n = nl.item(0);
>    while (n) {
> 	n.getParentNode().removeChild(n);
> 	i++;
> 	n = nl.item(i);
>    }
> 
> 
> It may be getting late on Friday, but I don't understand how either of
> these snippets deletes every OTHER paragraph; don't they delete EVERY
> paragraph???

Here's why ...

Suppose nl enumerates the following paras,

   0   1   2   3   4   5   6 <- node list index

  P0  P1  P2  P3  P4  P5  P6

Now, first time through your loop you delete the item at
index 0,

  P1  P2  P3  P4  P5  P6

Second time through you delete the item at index 1,

  P1  P3  P4  P5  P6

Third time through you delete the item at index 2,

  P1  P3  P5  P6

Then on your last iteration you delete the item at index 4.

  P1  P3  P5

Steve's code behaves in almost exactly the same way.

And, yes, I agree, this interface will be very error prone,
because noone expects things which look like arrays to
behave as NodeLists do.

Cheers,


Miles

-- 
Miles Sabin                          Cromwell Media
Internet Systems Architect           5/6 Glenthorne Mews
+44 (0)181 410 2230                  London, W6 0LJ
msabin@cromwellmedia.co.uk           England

Received on Friday, 16 October 1998 15:58:49 UTC