If you mean children, element instances have childNodes
(which includes non-element children like text nodes) and (on most engines) children
(which just has child elements). (You clarified you mean descendants.)
如果你的意思是后人, 您可以使用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
可迭代(你可以如果他们不这样做的话,可以简单地填充它 https://stackoverflow.com/a/46057817/157247),您还可以在 ES2015+ 环境中使用展开表示法:
var descendants = [...theElement.querySelectorAll("*")];
Example:
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>