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>
I'm think about recursion as one of options. At the first point I know parent
Element.
If You want to get list only children elements with id or class, avoiding elements without id/class, You can use document. getElementById('container'). querySelectorAll('[id],[class]'); ... querySelectorAll('[id],[class]') will "grab" only elements with id and/or class.
If you mean descendants, you can use querySelectorAll : var descendants = theElement. querySelectorAll("*");
getElementById('element-id') .
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).
If you mean descendants, you can use querySelectorAll
:
var descendants = theElement.querySelectorAll("*");
All modern browsers, and IE8, have querySelectorAll
.
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("*"));
Or you can use Array.from
(added in ES2015, but easily polyfilled):
var descendants = Array.from(theElement.querySelectorAll("*"));
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("*")];
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With