Re: An observation about "live" NodeLists

Mike Champion <mcc@arbortext.com> writes:

> At 12:15 PM 10/16/98 -0700, Stephen R. Savitzky wrote:
> >Question 1: What does the following code fragment do?
> >
> >1   NodeList nl = aDocument.getElementsByTagName("p");
> >2   int numberOfParagraphs = nl.getLength();
> >3   for (int i = 0; i < numberOfParagraphs; i++) {
> >4	Node n = nl.item(i);
> >5	n.getParentNode().removeChild(n);
> >6   }

> 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???

I think this proves my point.  After item 0 is deleted, the live NodeList
gets effectively re-indexed.  The paragraph that _used_ to be item 1 is now
item 0.  The paragraph that used to be item 2 is now item 1, so that gets
deleted next.  And so on.

> You might esthetically prefer to have exceptions thrown under "normal"
> conditions, but the only way we found to define and API that worked with
> both Java/C++ and C/ECMAScript was to use exceptions only for
> "exceptional" situations.  Thus, though it may be a bit uglier, DOM
> programmers have to work in the classic tradition of checking return codes
> rather than catching exceptions for routine navigation.

On the whole I prefer style myself, but as I believe I have shown, it's not
always obvious when you have to check.  

> So, yes I *do* think that naive script writers will tend to do the right
> thing with NodeLists.

I think that the naive script writer is more likely to write something like
my snippet (which blows up) or yours (which is written much more carefully
and so only has _one_ bug in it) and spend a lot of time head-scratching.

-- 
 Stephen R. Savitzky   Chief Software Scientist, Ricoh Silicon Valley, Inc., 
<steve@rsv.ricoh.com>                            California Research Center
 voice: 650.496.5710   fax: 650.854.8740    URL: http://rsv.ricoh.com/~steve/
  home: <steve@starport.com> URL: http://www.starport.com/people/steve/

Received on Friday, 16 October 1998 16:28:12 UTC