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

214
Views
appendChild function that could be called multiple times and make multiple elements with content in it

How am I supposed to convert this append child code to function, so I could make my code more readable and shorter? Also would it be possible to one of those childrens append another children, also created with this function?

let infoDiv = document.createElement("div");
infoDiv.classList.add("fullEventInfo");
classes.appendChild(infoDiv);

let titleTypeDiv = document.createElement("div");
titleTypeDiv.classList.add("titleType");
infoDiv.appendChild(titleTypeDiv);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use this:

function createElement(type, props, ...children) {
  const elem = document.createElement(type);

  if(props)
    Object.assign(elem, props);

  for(let child of children) {
    if(typeof child === "string")
      elem.appendChild(document.createTextNode(child))
    else
      elem.appendChild(child)
  }

  return elem;
}

So:

let elem = createElement("div", { className: "test" }, createElement("p", {}, "hello world !!!"));

This renders as:

<div class="test">
  <p>hello world !!!</p>
</div>
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!