A method for JavaScript first-order traversal of dom trees _javascript tips

Source: Internet
Author: User
Tags tagname

The DOM tree is a tree structure of all the nodes in the document (element nodes, text nodes, annotation nodes, etc.), and the parsing and building of the DOM tree is the key function that the browser implements. Now that the DOM tree is a tree structure, we can iterate over the DOM tree using the method of traversing the tree structure, while the "traversal" module in DOM2 provides two new types so that the first-order traversal of the DOM tree can be easily implemented.

Note: The 5 methods in this article are the first-order traversal method for the DOM (depth-first traversal) and focus on the element type only.

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

The DOM1 provides some APIs for the underlying type node, through which you can perform some basic DOM operations. The code for recursively traversing the DOM tree is simpler, with the core idea of dealing with the current node and then recursively traversing the child nodes from left to right, as follows:

/**
  * Use recursive way to first traverse the DOM tree
  * @param node root node/
 function Traversal (node) {
   //node processing
   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) {
       //recursive first-order traversal child node
       traversal (item)
     ;
   }
 }

2. Using the DOM1 interface, iterate through the DOM tree

The

differs from the 1th method, which uses an iterative approach to traverse the DOM tree. Using iterations to traverse the DOM tree is relatively complex, and the key point is to use a stack to maintain the access path of the node, when the current node is processed, the first element child node of the node is used as the root node of the next loop, and the other child element nodes of the current node are pressed into the stack in Right-to-left order. If the current node does not have an element child node, a single element node is popped from the stack as the root node of the next loop until the root node is removed. The code is as follows:

/**
 * Use an iterative approach to first traverse the DOM tree
 * @param node 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. Using the DOM-extended element traversal API to recursively traverse the DOM tree

The DomElement Traversal API provides several interfaces that facilitate DOM traversal, making it easier to obtain the element child nodes of a node. The element traversal API for DOM extensions is described in section 2nd of the DOM extension: further enhancements to the DOM API [summary]. The code is as follows:

/**
 * uses the DOM extended traversal API to provide a new interface for first-order traversal of the DOM tree
 * @param node 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 of Nodeiterator

The DOM2 "Traversal" module provides the Nodeiterator type, which makes it easy to implement the first-order traversal of the DOM tree, which is described in 12.3.1 of the JavaScript Advanced Programming Third Edition, where we give you the following code:

/**
 * uses the DOM2 "traversal" module to provide nodeiterator first-order Traversal DOM Tree
 * @param node 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 of Treewalker

The Treewalker type is an enhanced version of the Nodeiterator type, which is described in 12.3.2 of the third edition of JavaScript Advanced Programming, which we also give directly to the following code:

/**
 * uses the DOM2 "traversal" module to provide Treewalker first-order Traversal DOM Tree
 * @param node 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 you to share the JavaScript first sequence traversal dom tree method, hope for everyone's learning help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.