Created
March 23, 2018 13:35
-
-
Save jonurry/8415c955d8398fef03cae2dff4a8fdea to your computer and use it in GitHub Desktop.
14.1 Build a Table (Eloquent JavaScript Solutions)
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
| <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> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
You can use
document.createElementto create new element nodes,document.createTextNodeto create text nodes, and theappendChildmethod 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.keyswill be useful.To add the table to the correct parent node, you can use
document.getElementByIdordocument.querySelectorto find the node with the properidattribute.