querySelectorAll() returns every element matching a CSS selector. Use it through document to gather groups of page elements, or through an existing element to search within that element. section 14.1
Gathering painting tables
A data-extraction script selects all tables matching ".wikitable.sortable", then loops through each table and its "tbody tr" rows. It filters the tables by index, extracts painting details, and stores the results in an array. section 14.1
Use querySelectorAll() effectively by:
- Choosing a selector that is both common and unique to the elements you need. section 14.1
- Searching within each matched element when processing nested structures. section 14.1
- Expecting inconsistent real-world markup and handling missing values explicitly. section 14.1
Listing 14.1 Extracting data from Van Gogh’s paintings on Wikipedia
const tables = [ #1
{ index: 0, medium: "oil" },
{ index: 1, medium: "oil" },
{ index: 2, medium: "oil" },
{ index: 3, medium: "oil" },
{ index: 4, medium: "oil" },
{ index: 5, medium: "oil" },
{ index: 6, medium: "watercolor" },
{ index: 7, medium: "print" },
{ index: 8, medium: "print" },
];
const domTables = document.querySelectorAll( #2
".wikitable.sortable"
);
const paintings = []; #3
domTables.forEach((table, i) => { #4
if (i <= tables.length - 1) {
const medium = tables[i].medium;
const rows = table.querySelectorAll("tbody tr");
rows.forEach(row => {
let title; #5
if (row.querySelector(".thumbcaption i a")) {
title = row.querySelector(".thumbcaption i a")
.textContent;
} else if (row.querySelector(".thumbcaption i")) {
title = row.querySelector(".thumbcaption i")
.textContent;
} else {
title = null;
}
let imageLink; #6
if (row.querySelector(".thumbinner img")) {
const image = row.querySelector(
".thumbinner img"
).srcset;
imageLink = `https${image.slice(
image.indexOf("1.5x, ")+6,-3
)}`;
} else {
imageLink = null;
}
paintings.push({ #7
title: title,
imageLink: imageLink,
medium: medium
});
})
}
});
console.log(paintings); #8
Listing 14.1 demonstrates selecting tables, iterating through matches, selecting rows, and building painting data. section 14.1
