Return 所有 DOM 元素的数组,按深度排序

Return an array of all the DOM elements, sorted by depth

在 Javascript 中,如何创建 DOM 中所有元素的数组,按深度排序,所以它是这样的...

<body>
  <1stChild>
    <1stGrandchild>
  <2ndChild>
  <3rdChild>
    <2ndGrandchild>
    <3rdGrandchild>
      <1stGreatgrandchild>
      <2stGreatgrandchild>
    <4thGrandchild>
  <4thChild>
  <etc etc>

看起来像这样...

["body", "1stChild", "2ndChild", "...", "lastChild", "1stGrandchild", "...", "lastGrandchild", "1stGreatgrandchild", "...", "lastGreatgrandchild" "etc. etc."]

我有一个 jQuery solution 但想要一个纯的 javascript

这会修改 Crockford 的 walkTheDOM() 来完成您的需要。

var output = [], 
    currentCount = 0, 
    depth = 0;

function walkTheDOM(node, func) {
    currentCount++;
    depth++;
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
    depth--;
}

function getDepths(node) { 
    if (node.nodeType !== 3) {
        output.push ({ 
            node: node, 
            depth: depth, 
            encountered: currentCount
        }); 
    }
}

walkTheDOM(document.body, getDepths); 

output.sort(function(a, b) { 
    return a.depth === b.depth ? 
        a.encountered - b.encountered : 
        a.depth - b.depth; 
}); 

console.log(output);
<div class="first">
  <div class="second">
    <div class="third"></div>
    <div class="fourth">
      <div class="fifth"></div>
    </div>
  </div>
  <div class="sixth"></div>
  <div class="seventh">
    <div class="eighth"></div>
  </div>
  <div class="ninth"></div>
</div>
<div class="tenth"></div>

好吧,我自己想通了,最后还是挺简单的。

    // Every Element in the DOM.

var allElements = document.getElementsByTagName('*'),

    // All the Element's children sorted by depth, 
    // ie. body, then body's children, grandchildren,
    // so on and so forth.

    sortedByDepth = [];

    // for every element

for(var i = 0; i<allElements.length; ++i) {

    // grab Its children

    var allChildren = allElements[i].children;

    // for every grabbed child

    for(var j = 0; j<allChildren.length; ++j){

        // Add it to the sortedByDepth array

        sortedByDepth = sortedByDepth.concat(allChildren[j]);
    }   
}
console.log(sortedByDepth);