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
HTMLCollection
instance returned inArray.from
so 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
product
element, 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...