If you're referring to youngsters, then element instances contain childNodes
(which includes non-element children like text nodes) and, on most engines, children
(which specifically refers to child elements only). (You've clarified that you mean descendants.)
If by descendants, you can utilize querySelectorAll
:
var descendants = theElement.querySelectorAll("*");
All modern browsers, as well as IE8, support querySelectorAll
.
This returns a NodeList
, which is similar to an array. If you prefer a genuine JavaScript array, you can achieve it using Array.prototype.slice
, like so:
var descendants = Array.prototype.slice.call(theElement.querySelectorAll("*"));
Alternatively, you can utilize Array.from
(introduced in ES2015, but easy to polyfill):
var descendants = Array.from(theElement.querySelectorAll("*"));
Nowadays, since most environments have made NodeList
iterable (and you can easily polyfill it if not), you can also make use of spread notation in an ES2015+ environment:
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>