09. Latest 5 top stories

HTML

1
2
3
<div id="app">
<span id="placeholder"></span>
</div>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* For this project, get an array of stories from the New York Times API,
turn them into markup, and inject them into the #app element. */

const appOutput = document.querySelector('#app');
const getStories = function () {
fetch('https://api.nytimes.com/svc/topstories/v2/science.json?api-key=T6l8P8ICK6XZr1u3OeA0qoGUFrEcSM5R').then(
function (response) {
if (response.ok) {
return response.json()
} else {
return Promise.reject(response)
};
}).then(function (data) {
const allStories = [...data.results];
const lastFiveStories = allStories.slice(0, 5)
appOutput.innerHTML = lastFiveStories.map(function (result) {
return (`
<div class="container">
<ul class="title">
<li>${result.title}</li>
<a class="link" href="${result.url}" target="_blank">Read more</a>
</ul>
</div>
<br>
`);
}).join('')
}).catch(response => {
console.log("something went wrong", response);
appOutput.textContent = "Something went wrong...";
});
};

getStories();