HTML and CSS Reference
In-Depth Information
EXAMPLE
15.11 (
CONTINUED
)
</head>
<body>
18 <div id="TableContainer"></div>
</body>
</html>
EXPLANATION
1
The CSS style sheet will create the style for the table we are creating, including the
table itself, its heading, and cells.
2
When the page loads, the
startUp() f
unction will be called.
3
The next statements create the table, its header, and body for the DOM tree.
4
This array will contain the header values for the table.
5
This two-dimensional array contains the values that will go into the table cells.
6
Now that the table node has been created, we insert the table nodes into the main
DOM tree, at which point the browser can display it.
7
Next a row is created for the header in the table and a reference returned.
8
The row is inserted into the DOM tree for the header of the table.
9
This
for
loop will iterate for each cell needed to create the header of the table.
10
The cell for the header data is created.
11
From the array of data for the header (“State', “Capital”, and “Abbr”), the
in-
nerHTML
property will be assigned the data for a cell each time through the loop.
Next the data is appended to each of the cells.
12
This
for
loop will iterate until all the rows and cells have been filled for the table.
13
The table rows are created, one by one, and appended to the DOM tree.
14
This nested
for
loop will iterate through each of the cells in a row so that we can
access the data in the two-dimensional array created on line 5 and put it in the
table cells.
15
First we need to create a table cell for each row.
16
Once the table cell is created, the actual data from the two-dimensional array,
called
states
, must be inserted in each table cell and appended to the DOM struc-
ture.
17
A reference to the
div
container (line 18) is returned by the
getElementID()
meth-
od, and the entire completed table is appended to the
div
.
18
The HTML portion of this page is very small. It consists of
<div></div>
tags that
will hold the table built with the DOM methods and JavaScript. See Figure 15.21
the result.