如何获取父容器的所有后代元素? [英] How can I get all descendant Elements for parent container?
问题描述
如何获取父容器的所有后代元素?我想将它们放在数组中。
How can I get all descendant Elements for parent container? I want to get them in array.
<div class="parent">
<div class="child1">
<span class="child2">
<div class="child3">
<div class="child4">
<span class="child5"></span>
</div>
<div class="child6">
<div class="class7"></div>
</div>
</div>
</span>
<div class="child8"></div>
<span class="child9">
<div class="child10"></div>
</span>
</div>
</div>
我认为递归是一种选择。首先,我知道 parent
元素。
I'm think about recursion as one of options. At the first point I know parent
Element.
推荐答案
如果您是说 children ,则元素实例具有 (您澄清了您的意思是后裔。) childNodes
(包括文本元素之类的非元素子代)和(在大多数引擎上)子代
(仅具有子代元素)。
If you mean children, element instances have (You clarified you mean descendants.)childNodes
(which includes non-element children like text nodes) and (on most engines) children
(which just has child elements).
如果您的意思是后裔,则可以使用 querySelectorAll
:
If you mean descendants, you can use querySelectorAll
:
var descendants = theElement.querySelectorAll("*");
所有现代浏览器和IE8均具有 querySelectorAll
。
All modern browsers, and IE8, have querySelectorAll
.
它为您提供了一个 NodeList
,它类似于数组。如果您想要一个真正的JavaScript数组,则可以使用 Array.prototype.slice
来获取它,如下所示:
It gives you a NodeList
, which is array-like. If you want a true JavaScript array, you can use Array.prototype.slice
to get it, like this:
var descendants = Array.prototype.slice.call(theElement.querySelectorAll("*"));
或者您可以使用 Array.from
(在ES2015中添加,但易于填充):
Or you can use Array.from
(added in ES2015, but easily polyfilled):
var descendants = Array.from(theElement.querySelectorAll("*"));
现在大多数环境使 NodeList
变得可迭代(并且您可以对其进行简单填充(如果没有)),还可以在ES2015 +环境中使用扩展符号:
Now that most environments made NodeList
iterable (and you can polyfill it trivially if they don't), you can also use spread notation in an ES2015+ environment:
var descendants = [...theElement.querySelectorAll("*")];
示例:
var descendants = Array.prototype.slice.call(
document.querySelector(".parent").querySelectorAll("*")
);
descendants.forEach(function(descendant) {
display(descendant.className);
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
<div class="parent">
<div class="child1">
<span class="child2">
<div class="child3">
<div class="child4">
<span class="child5"></span>
</div>
<div class="child6">
<div class="class7"></div>
</div>
</div>
</span>
<div class="child8"></div>
<span class="child9">
<div class="child10"></div>
</span>
</div>
</div>
这篇关于如何获取父容器的所有后代元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!