如何获得所有的子节点在 JS 包括所有的“孙子”?

我想扫描所有的子节点的 div,包括其他元素中的子节点。现在我有这个:

var t = document.getElementById('DivId').childNodes;
for(i=0; i<t.length; i++) alert(t[i].id);

但它只能得到迪夫的孩子,而不是孙子。谢谢!

编辑: 这个问题太含糊了。对不起。这是一把小提琴:

Http://jsfiddle.net/f6l2b/

Onload 脚本不在 JSFiddle 上运行,但是它可以工作,除了“ Me Second”和“ Me Third”输入字段没有被分配 tabIndex,因此被跳过。

76135 次浏览

曾孙呢?

To go arbitrarily deep, you could use a recursive function.

var alldescendants = [];


var t = document.getElementById('DivId').childNodes;
for(let i = 0; i < t.length; i++)
if (t[i].nodeType == 1)
recurseAndAdd(t[i], alldescendants);


function recurseAndAdd(el, descendants) {
descendants.push(el.id);
var children = el.childNodes;
for(let i=0; i < children.length; i++) {
if (children[i].nodeType == 1) {
recurseAndAdd(children[i]);
}
}
}

If you really only want grandchildren, then you could take out the recursion (and probably rename the function)

function recurseAndAdd(el, descendants) {
descendants.push(el.id);
var children = el.childNodes;
for(i=0; i < children.length; i++) {
if (children[i].nodeType == 1) {
descendants.push(children[i].id);
}
}
}

如果你正在寻找现代浏览器上所有的 HTMLElement,你可以使用:

myDiv.querySelectorAll("*")

This is the fastest and simplest way, and it works on all browsers:

myDiv.getElementsByTagName("*")

如果还有其他人希望在这个树中包含所有的 节点,而不仅仅是 元素,这里有一个2022年的 JS 代码片段:

function getDescendantNodes(node, all = []) {
all.push(...node.childNodes);
for (const child of node.childNodes)
getDescendantNodes(child, all);
return all;
}

提示: 之后,您可以使用 Node全局: nodes = getDescendantNodes($0); nodes.filter(n => n.nodeType === Node.TEXT_NODE)过滤到您首选的 nodeType