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

An observation about "live" NodeLists

From: Stephen R. Savitzky <steve@crc.ricoh.com>
Date: 16 Oct 1998 12:15:33 -0700
To: <www-dom@w3.org>
Message-ID: <qcaf2w9v3e.fsf@gelion.crc.ricoh.com>
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.

Notes: 

   Caching the length of a NodeList in this way is the only reasonable thing
   to do in most cases, because computing it is so expensive.  The _correct_
   way of deleting all the paragraphs in a document is, of course, to
   replace line 3 with: 

3'  for (int i = numberOfParagraphs - 1; i >= 0; i--) {

   but I suspect that this might not be obvious to the ``naive'' script-
   writer. 

Question 2:  

   Is this really what you mean by catering to the needs of naive
   programmers? 

-- 
 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 15:11:06 GMT

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