Alex Alex - 1 month ago 5
Javascript Question

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>


I'm think about recursion as one of options. At the first point I know
parent
Element.

Answer

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.)

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#slice to get it, like this:

var descendants = Array.prototype.slice.call(theElement.querySelectorAll("*"), 0);

Example:

var descendants = Array.prototype.slice.call(
  document.querySelector(".parent").querySelectorAll("*"),
  0
);
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>

Comments