我有这样的HTML代码:
<div id="test">
<div id="test1">
<div id="test2">
test
</div>
</div>
</div>
我想获取元素“ test”的所有子元素,因此我做了一个递归函数:
function getObjectChildren(elem) {
var elemChildren = elem.childNodes;
var result = [];
result.push.apply(elemChildren);
for (k = 0; k < elemChildren.length; k++) {
if (elemChildren[k].childNodes.length > 0) {
result.push.apply(getObjectChildren(elemChildren[k]));
}
}
return result;
}
var a = getObjectChildren(document.getElementById("test");
事实是,此递归函数进入无限循环。有谁知道为什么会这样,我该如何解决呢?
最佳答案
我解决了我的问题:
function getObjectChildren(elem) {
var elemChildren = elem.childNodes;
var result = [];
for (var k = 0; k < elemChildren.length; k++) {
result.push(elemChildren[k]);
if (elemChildren[k].childNodes.length > 0) {
var tmp = getObjectChildren(elemChildren[k]);
for (var i = 0; i < tmp.length; i++) {
result.push(tmp[i]);
}
}
}
return result;
}