appendChild 函数,可以多次调用并生成多个包含内容的元素

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

我应该如何将此附加 child 代码转换为函数,以便使我的代码更具可读性和更短?也可以将其中一个 childrens 添加另一个 children,也是用这个函数创建的吗?

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

let titleTypeDiv = document.createElement("div");
titleTypeDiv.classList.add("titleType");
infoDiv.appendChild(titleTypeDiv);

使用这个:

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

所以:

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

呈现为:

<div class="test">
  <p>hello world !!!</p>
</div>