1. JavaScript, HTML, and the DOM
Activity 1: Extracting Data from a Page
Solution:
- Initialize a variable to store the entire content of the CSV:
var csv = 'name,price,unit\n';
- Query the DOM to find all the elements that represent each product. Notice how we wrap the
HTMLCollectioninstance returned inArray.fromso that we can handle it like a normal array:var elements = Array.from(document.getElementsByClassName('item')); - Iterate over each element found:
elements.forEach((el) => {}); - Inside the closure, using the
productelement, query to find the price with the unit. Split the string using a slash:var priceAndUnitElement = el.getElementsByTagName('span')[0]; var priceAndUnit = priceAndUnitElement.textContent.split("/"); var price = priceAndUnit[0].trim(); var unit = priceAndUnit[1].trim(); - Then query for the name:
var name = el.getElementsByTagName('a')[0].textContent; - Append all information to the variable...