javascript method of traversing the DOM tree in order

  • 2021-01-14 05:34:52
  • OfStack

DOM tree is a tree structure composed of all nodes (element nodes, text nodes, comment nodes, etc.) in the document. The parsing and construction of DOM tree is the key function to be realized by the browser. Since the DOM tree is a tree structure, we can use the method of traversing the tree structure to traverse the DOM tree. At the same time, the "Traversal" module in DOM2 provides two new types, so we can easily implement the pre-order traversal of the DOM tree.

Note: The five methods in this article are all pre-ordered traversal methods (depth-first traversal) for DOM and focus only on Element types.

1. Recursively traverse the DOM tree using the underlying interface in DOM1

DOM1 provides some api for the base type Node, with which some basic DOM operations can be performed. The code to recursively traverse the DOM tree is relatively simple. The core idea is to process the current node first, and then recursively traverse the child nodes from left to right. The code is as follows:


/**
  *  You iterate through it in a recursive way DOM The tree 
  * @param node  The root node 
  */
 function traversal(node){
   // right node The processing of 
   if(node && node.nodeType === 1){
     console.log(node.tagName);
   }
   var i = 0, childNodes = node.childNodes,item;
   for(; i < childNodes.length ; i++){
     item = childNodes[i];
     if(item.nodeType === 1){
       // Recursively traverses the child nodes in order first 
       traversal(item);
     }
   }
 }

2. Iterate through the DOM tree using the basic interface of DOM1

Unlike the first approach, this one uses an iterative approach to traverse the ES32en tree. Using iterative tree traversal DOM relatively complex 1, the key is to use a stack to maintain node access path, when dealing with the current node, the node first first Element child node as root node under one cycle, and in the order from right to left, to press the other child elements of the current node node into the stack. If the current node does not have one Element child node, then one Element node is popped from the stack as the root node of the next cycle until no root node is retrieved. The code is as follows:


/**
 *  Use an iterative approach to traverse first DOM The tree 
 * @param node  The root node 
 */
function traversalIteration(node){
  var array = [], i = 0,k = 0,elementCount = 0, len = 0, childNodes,item;
  while(node != null){
    console.log(node.tagName);
    childNodes = node.childNodes;
    len = node.childNodes.length;
    elementCount = 0;
    if(len > 0){
      for(i = 0; i < len; i++){
        item = childNodes[i];
        if(item.nodeType === 1){
          elementCount++;
          node = item;
          break;
        }
      }
      for(k = len -1 ; k > i; k--){
        item = childNodes[k];
        if(item.nodeType == 1){
          elementCount++;
          array.push(item);
        }
      }
      if(elementCount < 1){
        node = array.pop();
      }
    }else{
      node = array.pop();
    }
  }
}

3. Use the Element Traversal API extension to traverse the DOM tree recursively

DOMElement Traversal API provides several interfaces to facilitate DOM traversal, which makes it easier to obtain Element child nodes of one node. In section 2 of DOM Extension: Further Enhancements to DOM API [Summary - Part I], the Element Traversal Extension is introduced. The code is as follows:


/**
 *  use DOM The extended Traversal API The new interface provided is traversed in order DOM The tree 
 * @param node  The root node 
 */
function traversalUsingTraversalAPI(node){
  if(node && node.nodeType === 1){
    console.log(node.tagName);
  }
  var i = 0,len = node.childElementCount, child = node.firstElementChild;
  for(; i < len ; i++){
    traversalUsingTraversalAPI(child);
    child = child.nextElementSibling;
  }
}

4. Use NodeIterator

The "Traversal" module of DOM2 provides the NodeIterator type, which can be used to easily implement the DOM tree pre-order traversal. This type is introduced in Section 12.3.1 of JavaScript Advanced Programming Edition 3. Here is the code:


/**
 *  use DOM2 the "Traversal" Module provided NodeIterator The first sequence traversal DOM The tree 
 * @param node  The root node 
 */
function traversalUsingNodeIterator(node){
  var iterator = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT,null,false);
  var node = iterator.nextNode();
  while(node != null){
    console.log(node.tagName);
    node = iterator.nextNode();
  }
}

5. Use TreeWalker

The TreeWalker type is an enhanced version of the NodeIterator type. This type is described in Section 12.3.2 of JavaScript Advanced Programming 3rd Edition.


/**
 *  use DOM2 the "Traversal" Module provided TreeWalker The first sequence traversal DOM The tree 
 * @param node  The root node 
 */
function traversalUsingTreeWalker(node){
  var treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_ELEMENT,null,false);
  if(node && node.nodeType === 1){
    console.log(node.tagName);
  }
  var node = treeWalker.nextNode();
  while(node != null){
    console.log(node.tagName);
    node = treeWalker.nextNode();
  }
}

The above is for everyone to share the javascript pre-order traversal DOM tree method, I hope to help you learn.


Related articles: