How to get all the children from a DOM element and not only the immediate children and return them using JavaScript?
Asked
Active
Viewed 628 times
0
-
1Please clarify what you mean saying "not only the immediate children" ? – Ashot Nov 23 '15 at 07:07
-
1The correct term for "children and not only the immediate children" is **descendants**. – Nov 23 '15 at 08:07
2 Answers
1
Assuming that you want to get all the descendants of a DOM element, you may use *
in CSS-selectors:
#elem *
.className *
div *
For example, you can extract all descendants of elem
element using vanilla JS:
document.querySelectorAll('#elem *')
or jQuery
$('#elem *')
Demo: (result appears in console)
[].forEach.call(document.querySelectorAll('#elem *'), function(x) {
console.log(x);
});
<div id="notAnElem">
<a></a>
<i></i>
</div>
<div id="elem">
<div>
<a></a>
</div>
<i></i>
</div>
All descendants of `elem` should appear in console

Yeldar Kurmangaliyev
- 33,467
- 12
- 59
- 101
1
You can use this:
If the entire body -
var c = document.body.childNodes;
If a certain DIV -
var c = document.getElementById("myDIV").childNodes
The above will also include text nodes and comments nodes
And if you need only element nodes, use this -
var c = document.body.children;
Note: All the above variable are collection of elements that can be later iterated using for loop with 'c.length' as the limit.

Leyon Gudinho
- 91
- 2
- 11