在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一个
答案 0 :(得分:0)
这改变了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>
答案 1 :(得分:0)
好的,我自己弄清楚了,最后它很简单。
// 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);