DOM Level 2 Traversal module has an important interface called NodeIterator. This object can be used to traverse filtered lists of nodes or elements using a flat logical representation of the document structure.

After the iterator is created, the first node of the list is usually the root of the subtree and nextNode() and previousNode() methods can be used to get the next and previous node (if exist). When the nextNode() method returns a null, traversal can be considered as completed.

Methods of NodeIterator interface


The createNodeIterator() method creates a NodeIterator object.

Syntax for createNodeIterator()

document.createNodeIterator(root, nodeType, filter, entityRefExpansion);


  • root: Root node where the NodeIterator’s traversal starts.
  • nodeType: Integer that specifies the types of nodes to show. It is a bitwise OR'd list of Filter specification constants from the NodeFilter DOM interface, indicating which nodes to iterate over. Some of the constants are SHOW_ALL to show all nodes, SHOW_ATTRIBUTE to show attribute nodes, etc.
  • filter: User defined filter function that can filter nodes. This function as explained earlier returns FILTER_ACCEPT, FILTER_REJECT and FILTER_SKIP to help in filtering nodes.
  • entityRefExpansion: True here indicates that the contents of EntityReference nodes are visible.


The nextNode() method is used to find the next node relative to the current node in the NodeIterator object. If there is no next node available in the iterator, the null is returned, this can be used to check the end of iterator values in aloop.


The previousNode() method fetches the previous node relative to the current node in the NodeIterator object.


The detach() method is used to release the NodeIterator object.

Following example code demonstrates the use of NodeIterator. Filter function ‘myFilter’ helps in fetching only buttons. Also note that even though button with id ‘three’ was inside other HTML elements, they were also fetched in a list as we are using NodeIterator which flattens the structure of HTML and fetches all elements.

Example of NodeIterator interface methods and properties


›› go to examples ››