Unimpressed by NodeIterator


I just posted a run down of some of the new DOM Traversal APIs in Firefox 3.5. The first half of the post is mostly a recap of my old Element Traversal API post.

The second half of the post is all about the new NodeIterator API that was just implemented. For those that are familiar with some of the DOM TreeWalker APIs this will look quite familiar.

It’s my opinion, though, that this API is, at best, bloated, and at worst incredibly misguided and impractical for day-to-day use.

Observe the method signature of createNodeIterator:

  1. var nodeIterator = document.createNodeIterator(
  2.   root, // root node for the traversal
  3.   whatToShow, // a set of constants to filter against
  4.   filter, // an object with a function for advanced filtering
  5.   entityReferenceExpansion // if entity reference children so be expanded
  6. );

This is excessive for what should be, at most, a simple way to traverse DOM nodes.

To start, you must create a NodeIterator using the createNodeIterator method. This is fine except this method only exists on the Document node – which is especially strange since the first argument is the node which should be used as the root of the traversal. The first argument shouldn’t exist and you should be able to call the method on any DOM element, document, or fragment.

Second, in order to specify which types of nodes you wish to see you need to provide a number (which is the result of the addition of various constants) that the results will be filtered against. This is pretty insane so let me break this down. The NodeFilter object contains a number of properties representing the different types of nodes that exist. Each property has a number associated with it (which makes sense, this way the method can uniquely identify which type of node to look for). But then the crazy comes in: In order to select multiple, different, types of nodes you must OR together the properties to creating a resulting number that’ll be passed in.

For example if you wanted to find all elements, comments, and text nodes you would do:

NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT

I’m not sure if you can get a much more counter-intuitive JavaScript API than that (you can certainly expect little, to no, common developer adoption, that’s for sure).

Next, the filter argument accepts an object that has a method (called acceptNode) which is capable of further filtering the node results before being returned from the iterator. This means that the function will be called on every applicable node (as specified by the previous whatToShow argument).

Two points to consider:

  • The filter argument must be an object with a property named ‘acceptNode’ that has a function as a value. It can’t just be a function for filtering, it must be enclosed in a wrapper object. Update: Actually, this isn’t true – at least with Mozilla’s implementation you can pass in just a function. Thanks for the tip, Neil!
  • The argument is required (even though you can pass in null, making it equivalent to accepting all nodes).

The last argument, entityReferenceExpansion, comes in to play when dealing with XML entities that also contain sub-nodes (such as elements). For example, with XML entities, it’s perfectly valid to have a declaration like <!ENTITY aname "<elem>test</elem>"> and then later in your document have &aname; (which is expanded to represent the element). While this may be useful for XML documents it is way out of the scope of most web content (thus the argument will likely always be false).

So, in summary, createNodeIterator has four arguments:

  • The first of which can be removed (by making the method available on elements, fragments, and documents).
  • The second of which is obtuse and should be optional (especially in the case where all nodes are to be matched.
  • The third which requires a superfluous object wrapping and should be optional.
  • The fourth of which should be optional.

None of this actually takes into account the actual iteration process. If you look at the specification you can see that all the examples are in Java – and when seeing this a lot of the API decisions start to make more sense (not that it really applies to the world of web-based development, though). In JavaScript one doesn’t really use iterators, more typically an array is used instead. (In fact a number of helpers have been added in ECMAScript 5 which make the iteration and filtering process that much simpler.)

I’d like to propose the following, new, API that would exist in place of the NodeIterator API (dramatically simplifying most common interactions, especially on the web).

  1. // Get all nodes in the document
  2. document.getNodes();
  3.  
  4. // Get all comment nodes in the document
  5. document.getNodes( Node.COMMENT_NODE );
  6.  
  7. // Get all element, comment, and text nodes in the document
  8. document.getNodes( Node.ELEMENT_NODE, Node.COMMENT_NODE, Node.TEXT_NODE );

I’d also like to propose the following helper methods:

  1. // Get all comment nodes in the document
  2. document.getCommentNodes();
  3.  
  4. // Get all text nodes in a document
  5. document.getTextNodes();

Beyond finding elements, finding comments and text nodes are the two most popular queries types that I see requested.

Consider the code that would be required to recreate the above using NodeIterator:

  1. // Get all nodes in the document
  2. document.createNodeIterator(document, NodeFilter.SHOW_ALL, null, false);
  3.  
  4. // Get all comment nodes in the document
  5. document.createNodeIterator(document, NodeFilter.SHOW_COMMENT, null, false);
  6.  
  7. // Get all element, comment, and text nodes in the document
  8. document.createNodeIterator(document,
  9.     NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT,
  10.     null, false
  11. );

This proposed API would return an array of DOM nodes as a result (instead of an NodeIterator object). You can compare the difference in results between the two APIs:

NodeIterator API

  1. var nodeIterator = document.createNodeIterator(
  2.     document,
  3.     NodeFilter.SHOW_COMMENT,
  4.     null,
  5.     false
  6. );
  7.  
  8. var node;
  9.  
  10. while ( (node = nodeIterator.nextNode()) ) {
  11.     node.parentNode.removeChild( node );
  12. }

Proposed API

  1. document.getCommentNodes().forEach(function(node){
  2.     node.parentNode.removeChild( node );
  3. });

Another example, if we were to find all elements with a node name of ‘A’.

NodeIterator API

  1. var nodeIterator = document.createNodeIterator(
  2.     document,
  3.     NodeFilter.SHOW_ELEMENT,
  4.     {
  5.         acceptNode: function(node){
  6.           return node.nodeName.toUpperCase() === "A";
  7.         }
  8.     },
  9.     false
  10. );
  11.  
  12. var node;
  13.  
  14. while ( (node = nodeIterator.nextNode()) ) {
  15.     node.className = "found";
  16. }

Proposed API

  1. document.getNodes( Node.ELEMENT_NODE ).forEach(function(node){
  2.     if ( node.nodeName.toUpperCase() === "A" )
  3.         node.className = "found";
  4. });

Almost always, when finding some of the crazy intricacies of the DOM or CSS, you’ll find a legacy of XML documents and Java applications – neither of which have a strong application to the web as we know it or to the web as it’s progressing. It’s time to divorce ourselves from these decrepit APIs and build ones that are better-suited to web developers.

Update: An even better alternative (rather than using constants representing node types) would be something like the following:

  1. document.getNodes( Element, Comment, Text );

Just refer back to the back objects representing each of the types that you want.

Posted: June 19th, 2009


If you particularly enjoy my work, I appreciate donations given with Gittip.

54 Comments (Show Comments)



Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.


Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

Ukiyo-e Database and Search

Ukiyo-e.org

Japanese woodblock print database and search engine.


John Resig Twitter Updates

@jeresig

Infrequent, short, updates and links.


via Ad Packs