Home > Software engineering >  appendChild function that could be called multiple times and make multiple elements with content in
appendChild function that could be called multiple times and make multiple elements with content in

Time:01-06

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);

CodePudding user response:

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 >
  <p>hello world !!!</p>
</div>
  •  Tags:  
  • Related