function fetchData() {
fetch(URL)
.then(response => response.json())
.then(data => {
const dataContainer = document.getElementById('dataContainer');
// Extracting and displaying specific data
data.forEach(item => {
const headline = item.headline;
const paragraph = item.paragraph;
const itemElement = document.createElement('div');
itemElement.innerHTML = `<h2>${headline}</h2><p>${paragraph}</p>`;
dataContainer.appendChild(itemElement);
});
})
.catch(error => {
console.error('Error:', error);
});
}
fetchData();
The API response data is assumed to be an array of objects. The data.forEach() method is used to iterate over each object in the array. Within the loop, the headline and paragraph properties are extracted from each object.
A new div element is created for each item, and its content is set using template literals to include the extracted data. This creates a structured HTML markup with the headline as an h2 element and the paragraph as a p element.
Finally, the newly created div element is appended to the dataContainer element on your webpage, which will display each item separately.
`. – Liftoff Jun 11 '23 at 10:14