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

Re: An observation about "live" NodeLists

From: Mike Champion <mcc@arbortext.com>
Date: Fri, 16 Oct 1998 15:36:06 -0400
Message-Id: <3.0.5.32.19981016153606.00c55af0@pophost.arbortext.com>
To: steve@crc.ricoh.com (Stephen R. Savitzky), <www-dom@w3.org>
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   }
>
>Answer:
>
>   It deletes all of the odd-numbered paragraphs in aDocument, and finally
>   throws a null pointer exception (NOT a DOMException, since item throws no
>   exceptions) on line 5 when i > numberOfParagraphs/2.  Of course, in a
>   language like C++ on an OS like Windows, it simply crashes.

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

Anyway, a couple of more serious points: The DOM API has to work with both
Java --  which fully supports exceptions and whose programmers are used to
having exceptions thrown when boundaries are reached -- and ECMAScript,
whose only conception of an exception is to put up an error dialog.  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.

So, yes I *do* think that naive script writers will tend to do the right
thing with NodeLists.
Received on Friday, 16 October 1998 15:36:56 GMT

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