Last active
September 22, 2019 18:44
-
-
Save ermauliks/e057ab4925b3f30591cf182f96b38f0c to your computer and use it in GitHub Desktop.
Dynamically create table inside DOM
This file contains 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
var mountains = [ | |
{ name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" }, | |
{ name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" }, | |
{ name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" }, | |
{ name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" }, | |
{ name: "Monte Amiata", height: 1738, place: "Siena" } | |
]; | |
String.prototype.firstUpper = function() { | |
return this.charAt(0).toUpperCase() + this.slice(1); | |
} | |
function generateTableHead(table, data) { | |
var thead = table.createTHead(); | |
var row = table.insertRow(); | |
for (let i=0; i < data.length; i++) { | |
var th = document.createElement('th'); | |
th.style.color = 'red'; | |
th.style.textAlign = 'left'; | |
var text = document.createTextNode(data[i].firstUpper()); | |
th.appendChild(text); | |
row.appendChild(th); | |
} | |
} | |
function generateTableBody(table, data) { | |
for (let i=0; i < data.length; i++) { | |
var row = table.insertRow(); | |
for (let key in data[i]) { | |
var cell = row.insertCell(); | |
var text = document.createTextNode(data[i][key]); | |
cell.appendChild(text); | |
} | |
} | |
} | |
var table = document.querySelector('table'); | |
table.style.width = '100%'; | |
generateTableHead(table, Object.keys(mountains[0])); | |
generateTableBody(table, mountains); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment