Session 7: JavaScript - IIII
Clone the following repository: Repo.
If you open the console, you should see there is an array that contains 100 objects. The objects have the following structure:
{ "userId": 1, "id": 1, "title": "sunt aut facere ...", "body": "quia et …" }
Task 1: Starting from the following code, try to output these objects to the HTML page, and you should have an HTML page that looks like the Figure below:
Hint: For each object, create a div and represent the title of each object in a <h3>
tag and its body in a <p>
tag, which both should be appended to the div. Then, append the div to the <body>
tag.
fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then(json => { console.log(json); // your code will be here }
Task 2: Do the required modifications to apply the ‘post’ class style defined in the style.css to the div, i.e., you should add a class with the name ‘post’ to each created div.
Task 3: Copy the content of https://jsonplaceholder.typicode.com/posts to myjson.json
, which is located in the res/json/
directory. Then, do the required modifications to fetch this data locally instead of fetching it from the online source.
Note: there should be no difference in the HTML page appearance, i.e., it should look exactly the same.
Task 4: Add the following .catch(err =>{..})
snippet, and try to produce an error in the fetch by modifying the link to the URI making it invalid. What do you observe?
.catch(err => { let errDiv = document.createElement("div"); errDiv.className = 'post'; errDiv.innerText = err; document.body.appendChild(errDiv); })
Task 5: Add the following .finally(() => {..})
snippet, try to run your code: (1) the fetch() produce an error; and (2) the fetch() do not produce an error. What do you observe?
.finally(() => { let footer = document.createElement("footer"); date = new Date().toLocaleString() footer.innerText = date; document.body.appendChild(footer); })
Task 6: Try to improve the appearance of the HTML page by defining different styles for the title (<h3>
tag) and the body (<p>
tag) of each object.
Note: You can use the tag selectors or define new classes for them.
Do it yourself:
1. Use a JSON Editor (e.g., https://jsoneditoronline.org/) to create several JSON objects (e.g., an array of objects) that have the same structure. Each object should cover all JSON data types (e.g., string, number, Boolean, object, array, and null).
2. After validating the objects array, i.e., it does not contain any errors. Save it to a local file or use a JSON store (API) ( https://www.npoint.io/) to put it online.
3. Using Fetch API, try to fetch the data (locally and/or online) and output them to an HTML page, the page should accommodate the data included in the JSON file according to their types. For example, each JSON object should be allocated to a div, then, create an appropriate HTML element for each data type, and append them to the div, which in turn should be appended to the document.