如何获取父容器的所有后代元素?我想让它们排成一列。
<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
元素。
最佳答案
如果您指的是 children,元素实例有 (你澄清了你的意思是后代。)childNodes
(包括非元素子节点,如文本节点)和(在大多数引擎上)children
(它只有子元素)。
如果你的意思是后代,你可以使用querySelectorAll
:
var descendants = theElement.querySelectorAll("*");
所有现代浏览器和 IE8 都有 querySelectorAll
。
它为您提供了一个类似于数组的 NodeList
。如果你想要一个真正的 JavaScript 数组,你可以使用 Array.prototype.slice
来获取它,就像这样:
var descendants = Array.prototype.slice.call(theElement.querySelectorAll("*"));
或者您可以使用 Array.from
(在 ES2015 中添加,但很容易填充):
var descendants = Array.from(theElement.querySelectorAll("*"));
现在大多数环境都使 NodeList
可迭代(您可以 polyfill it trivially if they don't ),您还可以在 ES2015+ 环境中使用扩展符号:
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>
关于javascript - 如何获取父容器的所有后代元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26325278/