Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created March 23, 2018 13:35
Show Gist options
  • Select an option

  • Save jonurry/8415c955d8398fef03cae2dff4a8fdea to your computer and use it in GitHub Desktop.

Select an option

Save jonurry/8415c955d8398fef03cae2dff4a8fdea to your computer and use it in GitHub Desktop.
14.1 Build a Table (Eloquent JavaScript Solutions)
<h1>Mountains</h1>
<div id="mountains"></div>
<script>
const MOUNTAINS = [
{name: "Kilimanjaro", height: 5895, place: "Tanzania"},
{name: "Everest", height: 8848, place: "Nepal"},
{name: "Mount Fuji", height: 3776, place: "Japan"},
{name: "Vaalserberg", height: 323, place: "Netherlands"},
{name: "Denali", height: 6168, place: "United States"},
{name: "Popocatepetl", height: 5465, place: "Mexico"},
{name: "Mont Blanc", height: 4808, place: "Italy/France"}
];
function createTable(tableData) {
let table = document.createElement('table');
// create table headings
let tableRow = document.createElement('tr');
table.appendChild(tableRow);
for (let column of Object.keys(tableData[0])) {
let th = document.createElement('th');
tableRow.appendChild(th);
th.appendChild(document.createTextNode(column));
}
// create table data rows
for (let row of tableData) {
let tr = document.createElement('tr');
table.appendChild(tr);
for (let data of Object.keys(row)) {
let td = document.createElement('td');
tr.appendChild(td);
td.appendChild(document.createTextNode(row[data]));
if (typeof(row[data] === 'number')) {
td.style.textAlign = 'right';
}
}
}
return table;
}
document.querySelector('#mountains').appendChild(createTable(MOUNTAINS));
</script>
@jonurry

jonurry commented Mar 23, 2018

Copy link
Copy Markdown
Author

Hints

You can use document.createElement to create new element nodes, document.createTextNode to create text nodes, and the appendChild method to put nodes into other nodes.

You’ll want to loop over the key names once to fill in the top row and then again for each object in the array to construct the data rows. To get an array of key names from the first object, Object.keys will be useful.

To add the table to the correct parent node, you can use document.getElementById or document.querySelector to find the node with the proper id attribute.

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