Ad

AppendChild Function That Could Be Called Multiple Times And Make Multiple Elements With Content In It

- 1 answer

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

Answer

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>
Ad
source: stackoverflow.com
Ad