Created
January 27, 2019 17:37
-
-
Save anxp/5778493f324cb60230d0437147ec2ebb to your computer and use it in GitHub Desktop.
Javascript table generation function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This function generates simple table with header row from specified data (tableContent, headerLabels). | |
* tableContent is 2-D array with DOM Elements as values: | |
* [ | |
* 0 => [0 => DOM_Obj_1cell_1row, 1 => DOM_Obj_2cell_1row, 2 => DOM_Obj_3cell_1row, ...], <- first row | |
* 1 => [0 => DOM_Obj_1cell_2row, 1 => DOM_Obj_2cell_2row, 2 => DOM_Obj_3cell_2row, ...], <- second row | |
* ]; | |
* headerLabels is 1-D array, also with DOM Elements as values (not just strings!); | |
* [ | |
* 0 => DOM_Obj_headerlabel_1, 1 => DOM_Obj_headerlabel_2, ... | |
* ]; | |
* tableClass and tableID are just strings; | |
*/ | |
function createTable(tableContent, headerLabels, tableClass = "", tableID = "") { | |
let tbl = document.createElement('table'); | |
tbl.classList.add(tableClass); | |
tbl.id = tableID; | |
//Create and fill container for header row (<thead></thead>): | |
let thead = document.createElement('thead'); | |
let tr = document.createElement('tr'); | |
for (let i = 0; i < headerLabels.length; i++) { | |
let th = document.createElement('th'); | |
th.appendChild(headerLabels[i]); | |
tr.appendChild(th); | |
} | |
thead.appendChild(tr); | |
tbl.appendChild(thead); | |
//Create and fill container for main table content (<tbody></tbody>): | |
let tbody = document.createElement('tbody'); | |
let rowsNum = tableContent.length; //Calculate how much rows will be in our table. | |
for (let r = 0; r < rowsNum; r++) { | |
tr = tbody.insertRow(); //Create new row and insert it to <tbody>; | |
let colsNum = tableContent[r].length; | |
for (let c = 0; c < colsNum; c++) { | |
let td = tr.insertCell(); | |
td.appendChild(tableContent[r][c]); | |
} | |
} | |
tbl.appendChild(tbody); | |
return tbl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment