Created
May 21, 2018 16:02
-
-
Save zeraphie/5465446dacbe040b1e1097774440eb03 to your computer and use it in GitHub Desktop.
Create an HTMLElement table from a json response from a database query
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
export default class DataTable { | |
/** | |
* Add the dataset (from a database query) to the class instance and also | |
* contain the attributes for the table element | |
* | |
* @param {json} | |
* @param {Object} | |
*/ | |
constructor(data, attributes = {}){ | |
this.data = data; | |
this.attributes = attributes; | |
} | |
/** | |
* Generate the table html element from the data provided | |
* | |
* @return {HTMLElement} | |
*/ | |
table(){ | |
let table = document.createElement('table'); | |
table.appendChild(this.thead()); | |
table.appendChild(this.tbody()); | |
for(let attribute in this.attributes){ | |
table.setAttribute(attribute, this.attributes[attribute]); | |
} | |
return table; | |
} | |
/** | |
* Generate the thead html element from the first row of data's columns | |
* | |
* @return {HTMLElement} | |
*/ | |
thead(){ | |
let thead = document.createElement('thead'); | |
let tr = this.constructor.tr(); | |
for(let column in this.data[0]){ | |
let th = this.constructor.th(column); | |
tr.appendChild(th); | |
} | |
thead.appendChild(tr); | |
return thead; | |
} | |
/** | |
* Generate the tbody html element from the full dataset | |
* @return {HTMLElement} | |
*/ | |
tbody(){ | |
let tbody = document.createElement('tbody'); | |
this.data.map(row => { | |
let tr = this.constructor.tr(); | |
for(let column in row){ | |
let td = this.constructor.td(column, row[column]); | |
tr.appendChild(td); | |
} | |
tbody.appendChild(tr); | |
}); | |
return tbody; | |
} | |
/** | |
* Create a basic tr html element | |
* | |
* @return {HTMLElement} | |
*/ | |
static tr(){ | |
let tr = document.createElement('tr'); | |
return tr; | |
} | |
/** | |
* Create a basic th html element | |
* | |
* @return {HTMLElement} | |
*/ | |
static th(value){ | |
let th = document.createElement('th'); | |
th.innerText = value; | |
return th; | |
} | |
/** | |
* Create a basic td html element with a data-column attribute | |
* | |
* @return {HTMLElement} | |
*/ | |
static td(column, value){ | |
let td = document.createElement('td'); | |
td.innerText = value; | |
td.setAttribute('data-column', column); | |
return td; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment