W3C home > Mailing lists > Public > www-dom@w3.org > October to December 1998

RE: An observation about "live" NodeLists

From: Miles Sabin <msabin@cromwellmedia.co.uk>
Date: Fri, 16 Oct 1998 20:53:35 +0100
Message-ID: <c=US%a=_%p=Cromwell_Media%l=ODIN-981016195335Z-23368@odin.cromwellmedia.co.uk>
To: "'Mike Champion'" <mcc@arbortext.com>, "'www-dom@w3.org'" <www-dom@w3.org>
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 GMT

This archive was generated by hypermail 2.2.0+W3C-0.50 : Friday, 22 June 2012 06:13:45 GMT