This is an old revision of the document!
We'll continue building our table of stats on the Colombia team, but we'll do it more efficiently with javascript by using arrays and loops.
<tbody>
tag. ie. delete all the data and leave only the heading.HTML
<table> <thead> <tr> <th>Name</th> <th>Surname</th> <th>Nationality</th> <th class="age">Age</th> <th>Position</th> </tr> </thead> <tbody> </tbody> </table>
CSS
td, th { border-width: 1px; border-style: solid; } td { padding-left: 10px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px; } table { border-collapse: collapse; } #carlos { font-style: italic; } .age { background-color: yellow; } #carlos .age { font-weight: 900; } td.age { font-size: 150%; }
[]
ospinaRemirez = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero'];
=
means we are assigning a value to the variable 'ospinaRemirez'.=
is [
so the value must be an array.,
and ends with ]
.;
.statsRow = "<td>" + ospinaRamirez[0] + "</td>";
"
symbols.0
, so the name is referred to as ospinaRamirez[0]
.+
symbol.statsRow = statsRow + "<td>" + ospinaRamirez[1] + "</td>";
statsRow
(new string) = statsRow
(old string) + additional elements.statsRow += "<td>" + ospinaRamirez[2] + "</td>"; statsRow += "<td>" + ospinaRamirez[3] + "</td>"; statsRow += "<td>" + ospinaRamirez[4] + "</td>";
+=
additional elements, but it means the same thing. We could have written the third line the same way, but it's good to see the different options so you can choose one you like.// add row to table
//
which means it's a comment. It tells us what the next bit of the program does, but your computer doesn't read this information. We now know that the next section of code is meant to add the row to our table.tableBody = document.getElementsByTagName("tbody")[0];
<tbody>
in the document (which is our page).<tbody>
in the page, so getElementsByTagName
returns a list and we need to identify which item in the list we want. In this case, it's the first so we use [0]
.tableBody
so we can refer to it in subsequent lines of code.newRow = tableBody.insertRow(0);
<tbody>
tag) of our tableBody element.newRow
newRow.innerHTML = statsRow;
newRow
..innerHTML
refers to the HTML code inside the element before the .
, so we're now talking about the code inside our new row.=
so we're going to assign something to the new row.statsRow
which is the string containing all the data cells.<tbody>
.ospinaRamirez = ['David', 'Ospina Ramirez', 'Colombia', 33, 'Portero']; statsRow = "<td>" + ospinaRamirez[0] + "</td>"; statsRow += "<td>" + ospinaRamirez[1] + "</td>"; statsRow += "<td>" + ospinaRamirez[2] + "</td>"; statsRow += "<td>" + ospinaRamirez[3] + "</td>"; statsRow += "<td>" + ospinaRamirez[4] + "</td>"; // add row to table tableBody = document.getElementsByTagName("tbody")[0]; newRow = tableBody.insertRow(0); newRow.innerHTML = statsRow;