How to retrieve all the DOM elements in a recursive function?

For learning purposes try to accomplish the task: to build a visual tree of DOM elements in a certain div.
Wrote this code, could bring the child elements of the Body, can not think of how the elements of the 2nd level and deeper to bring everyone in your parent div.
function showDOM(node) {
 for(var i=0; i < node.children.length; i++){
 var n = node.children[i],
 nParent = n.parentNode,
 el = document.createElement("div"),
 dom = document.getElementById("dom");
 if(n.id != "dom" && n.tagName != "SCRIPT"){
 el.innerText = n.tagName + "" + i;
 if(nParent.tagName == "BODY"){
dom.appendChild(el);
 } else {
 // Here I want to work with nested children elements BODY 
}
showDOM(node.children[i]);
}
}
}
 showDOM(document.body);


and html


<div class="level1">
 <div class="level2">
 <p class="level3"></p>
</div>
</div>
<ul class="level1">
 <li class="level2">
 <p class="level3"></p>
</li>
</ul>
<div id="dom">
</div>

I will be glad to any Council!
July 9th 19 at 10:52
3 answers
July 9th 19 at 10:54
Here's an example of a pictorial representation of the tree.
Interesting solution, thanks, but the problem was that to repeat the nesting of the elements. - Sadye commented on July 9th 19 at 10:57
July 9th 19 at 10:56
did not run,but recursion and so it is. why the test body is not clear.
Really all the logic should be to enumerate the children, listing only the recursive call.
July 9th 19 at 10:58
All the same solved the problem
$(document).ready(function() {
 "use strict";

 var recursionCount = 0,
 elements = [],
 dom = document.getElementById("dom");
 function showDOM(node) {
 for(var i=0; i < node.children.length; i++){
 var n = node.children[i],
 el = document.createElement("div"),
 elClass = n.className,
 parentNode = n.parentNode,
parent;
 if(n.id != "dom" && n.tagName != "SCRIPT"){
 n.setAttribute("id", recursionCount);
 el.setAttribute("data-element-id", recursionCount);
recursionCount++;
 if(n.parentNode.tagName == "BODY"){
 parent = "dom";
 } else {
 parent = parentNode.getAttribute("id");
}
 el.setAttribute("data-parent-id", (parent));
 el.innerText = "<" + n.tagName + " class='" + elClass + "'> recursionCount = " + recursionCount;
console.log(el);
elements.push(el);
}
showDOM(node.children[i]);
}
 return elements;
}
showDOM(document.body);
 for(var a in elements){
 var pasteIn = elements[a].getAttribute("data-parent-id"),
 all = document.getElementsByTagName("*");
 for(var b = 0; b < all.length; b++){
 if(all[b].getAttribute("data-element-id") == pasteIn){
all[b].appendChild(elements[a]);
}
}
}
});
Can plz explain how it work? ); - Sadye commented on July 9th 19 at 11:01
my vk vk.com/AmaTsuku - nikita.Stracke commented on July 9th 19 at 11:04

Find more questions by tags JavaScript