Javascript 如何获取JS中的所有子节点,包括所有“孙子”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8321874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get all childNodes in JS including all the 'grandchildren'?
提问by Mike
I want to scan a div for all childNodes including the ones that are nestled within other elements. Right now I have this:
我想扫描所有子节点的 div,包括那些位于其他元素中的子节点。现在我有这个:
var t = document.getElementById('DivId').childNodes;
for(i=0; i<t.length; i++) alert(t[i].id);
But it only gets the children of the Div and not the grandchildren. Thanks!
但它只获取 Div 的子项而不是孙子项。谢谢!
Edit: This question was too vague. Sorry about that. Here's a fiddle:
编辑:这个问题太模糊了。对于那个很抱歉。这是一个小提琴:
The body.onload script doesn't run at JSFiddle, but it works, except that the 'Me Second' and 'Me Third' input fields are not being assigned a tabIndex and are therefore being skipped over.
body.onload 脚本不在 JSFiddle 上运行,但它可以工作,除了“我第二个”和“我第三个”输入字段没有分配 tabIndex 并因此被跳过。
回答by rvighne
This is the fastest and simplest way, and it works on all browsers:
这是最快和最简单的方法,它适用于所有浏览器:
myDiv.getElementsByTagName("*")
回答by Mad Echet
If you're looking for all HTMLElement
on modern browsers you can use:
如果您正在HTMLElement
现代浏览器上寻找所有内容,您可以使用:
myDiv.querySelectorAll("*")
回答by Adam Rackis
What about great-grandchildren?
曾孙怎么办?
To go arbitrarily deep, you could use a recursive function.
要任意深入,您可以使用递归函数。
var alldescendants = [];
var t = document.getElementById('DivId').childNodes;
for(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(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);
}
}
}