Objects from the Page
A teacher has a printed class list. She types it into a spreadsheet, one row for each pupil, so the computer can sort it and count it. Your flight table is on the page, but for a script, it's only cells of text. When you turn its rows into objects, it becomes data the script can really work with.
One object for each row
const players = [];
for (const row of document.querySelectorAll("#scores tbody tr")) {
players.push({
name: row.querySelector(".name").textContent,
points: Number(row.querySelector(".points").textContent),
});
}
console.log(players);
[{name: "Sam", points: 12}, {name: "Lea", points: 9}]
Step by step:
- start with an empty array,
[]; - for each row of the table's body, make an object;
row.querySelector(".name")looks for.nameinside that row only.querySelectorworks on any element, not only ondocument;pushthe object onto the array.
After the loop, players holds one object for each row, with real numbers where the page has numbers.
Why do it?
Once the data is in objects, the rest of the script never has to look in the HTML again: players[0].points, players.length, a loop over players. In the next lessons, you will filter and sort this kind of list.
Break it on purpose
Look for the cell in the whole document, not in the row:
name: document.querySelector(".name").textContent,
Every object gets the first row's name. document.querySelector always finds the first .name on the page. Inside a loop over rows, ask the row.
Mission: The board as data
What you will see: when schedule.html opens, the console shows:
Flights read: 5
Last on the board: SL-105 to Orbital Yard
The schedule's script reads the flight table into a list of objects, one for each flight.
- In
schedule.js, an array namedflightsholds an object for each row of the flight table's body. - Each object has the row's
code,destination,departsandstatus, read from that row's cells. - The console shows
Flights read:, then how many objects the array has. - The console shows
Last on the board:, then the last object's code,to, and its destination.