forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13_1_build_a_table.html
More file actions
44 lines (37 loc) · 1.13 KB
/
13_1_build_a_table.html
File metadata and controls
44 lines (37 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!doctype html>
<base href="http://eloquentjavascript.net/">
<script src="code/mountains.js"></script>
<style>
/* Defines a cleaner look for tables */
table { border-collapse: collapse; }
td, th { border: 1px solid black; padding: 3px 8px; }
th { text-align: left; }
</style>
<body>
<script>
function buildTable(data) {
var table = document.createElement("table");
var fields = Object.keys(data[0]);
var headRow = document.createElement("tr");
fields.forEach(function(field) {
var headCell = document.createElement("th");
headCell.textContent = field;
headRow.appendChild(headCell);
});
table.appendChild(headRow);
data.forEach(function(object) {
var row = document.createElement("tr");
fields.forEach(function(field) {
var cell = document.createElement("td");
cell.textContent = object[field];
if (typeof object[field] == "number")
cell.style.textAlign = "right";
row.appendChild(cell);
});
table.appendChild(row);
});
return table;
}
document.body.appendChild(buildTable(MOUNTAINS));
</script>
</body>