Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Call a Function inside a innerHTML
.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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I made up my own testing data and played around with your code a bit. These were the points I found:

  • Your recursive function renderTree() always placed elements directly into the .container div. This should only happen for the outer call.
  • You did not 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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!