DOM depth-first traversal algorithm

By depth-first traversal algorithm, can in turn get the object for each descendant node.

Order: there are child elements to get the child element, and then get siblings

There are two main steps:

// 1. Create a node iterator object (parent to traverse node)

var iterator = document.createNodeIterator(parent, NodeFilter.SHOW_ELEMENT, null, false);

// 2. NextNode method of repeatedly calling iterator skip to the next

do{

  var node = iterator.nextNode();

  if(node !=  null) console.log(node.nodeName);

  else break;

}while(true);

Above can also be achieved using recursion, but recursion is low efficiency, it is not recommended.

Guess you like

Origin www.cnblogs.com/1016391912pm/p/11912503.html