Search code examples
javascriptfunctioncallbackappendchild

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

Solution

  • 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>