Reputation: 3011
I'm using DOMParser()
to parse a HTML string, and am trying to get all the child nodes with a for loop. However I do not know how to get the child nodes' nodes, and their children, etc...
var str = "<div><p>paragraph<span>span</span></p></div>";
var doc = new DOMParser().parseFromString(str, 'text/html');
var childnodes = doc.body.childNodes;
for (var i = 0; i < childnodes.length; i++) {
console.log(childnodes[i]);
console.log(childnodes[i].childNodes);
console.log(childnodes[i].childNodes[i].childNodes);
}
This works as I'd like, it gives the div
, p
, text
, and span
, but how would I make this work with a for loop that gets all the grandchildren? Without jQuery?
Here's a fiddle with the above code.
Upvotes: 1
Views: 218
Reputation: 9846
For those who can use jQuery, you could do it in a while
loop.
var $children = $(document.body).children();
while ($children.length) {
console.log($children.attr('class'));
$children = $children.children();
}
Or as @adeneo suggested, you can use contents()
:
$(document.body).find('*').contents();
Although, jQuery recommends to "Avoid the All Selector," either way it's likely going to be expensive code.
Upvotes: 1
Reputation: 16068
You should use recursion for this:
function travelChildren(childnodes){
for (var i = 0; i < childnodes.length; i++) { // for each node in childnodes
console.log(childnodes[i]); // console log current node
travelChildren(childnodes[i].childNodes) // and travel its children
}
}
travelChildren(childnodes) // start recursion with the child nodes you want
Upvotes: 3