.then(function renderTree (data){
Object.entries(data).map((item, index) => {
let container = document.querySelector(".container")
let li = document.createElement("li")
li.id = `${item[1].id}`
container.appendChild(li)
let span = document.createElement("span")
span.innerHTML = `${item[1].name}`
li.appendChild(span)
let ul = document.createElement("ul")
ul.innerHTML = renderTree(item[1].children)
li.appendChild(ul)
// gerarLi(item[1].id, item[1].name)
})
})
I trying to continue the childs inside a <ul>, the continuation is in:
ul.innerHTML = renderTree(item[1].children)
But this code doesn't work, my index.html return like:
<ul>undefined</ul>
What can I do for this?
I made up my own testing data and played around with your code a bit. These were the points I found:
renderTree() always placed elements directly into the .container div. This should only happen for the outer call.return anything from your renderTree() function.I changed the function such that it now returns an HTML-string to be placed inside a <ul> structure. This function can now safely be called recursively.
const data={abc:{id:"first",name:"number one"}, def:{id:"second",name:"el segundo"},
ghi:{id:"third",name:"der dritte",
children:{jkl:{id:"fourth",name:"child one"},mno:{id:"fifth",name:"child two"}}}};
function renderTree(data){ // returns an HTML string for a <UL> DOM element
return Object.values(data).map(({id,name,children}) => {
let li = document.createElement("li");
li.id = id;
let span = document.createElement("span");
span.innerHTML = name;
li.appendChild(span);
let ul = document.createElement("ul");
if (children){
ul.innerHTML = renderTree(children);
li.appendChild(ul);
}
return li.outerHTML;
}).join("\n");
}
document.querySelector(".container").innerHTML=renderTree(data);
span {color:blue}
<ul class="container"></ul>
I also changed the Object.entries() to Object.values() since you never use the keys of the processed objects.