Skip to content

Instantly share code, notes, and snippets.

@Sulkar
Created February 8, 2022 20:10
Show Gist options
  • Save Sulkar/5317435e06479f35107d842feb375704 to your computer and use it in GitHub Desktop.
Save Sulkar/5317435e06479f35107d842feb375704 to your computer and use it in GitHub Desktop.
Javascript: universal Create Element function
//universal Create Element function
function createElement(type, props, ...children) {
let dom = document.createElement(type);
if (props) Object.assign(dom, props);
for (let child of children) {
if (typeof child != "string" && typeof child != "number")
dom.appendChild(child);
else dom.appendChild(document.createTextNode(child));
}
return dom;
}
@Sulkar
Copy link
Author

Sulkar commented Feb 8, 2022

Usage, creates a table:

function createDataTable(tableId, dataResult) {
  let dataTable = document.getElementById(tableId);
  let dataTableHead = createElement("thead", {});
  let dataTableTr = createElement("tr", {});
  //create header columns
  Object.keys(dataResult[0]).forEach((headerItem) => {
    dataTableTr.appendChild(createElement("th", {}, headerItem));
  });
  dataTableHead.appendChild(dataTableTr);
  dataTable.appendChild(dataTableHead);

  //create rows with items
  let dataTableBody = createElement("tbody", {});
  dataResult.forEach((row) => {
    let dataTableBodyTr = createElement("tr", {});
    Object.values(row).forEach((item) => {
      dataTableBodyTr.appendChild(createElement("td", {}, item, createElement("button", {}, "Test")));
    });
    dataTableBody.appendChild(dataTableBodyTr);
  });

  dataTable.appendChild(dataTableBody);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment