In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript.
Currently, I am faced with the challenge of having to create separate div elements each time I want to add new data to one of my article fields. This process is becoming messy as I aim to populate multiple articles with this data without the need to continuously create new divs.
Is there a way to optimize this by having a single article-image div and dynamically generating new ones to populate them with API data based on array values?
var url =
"HIDDEN_API_KEY";
// Fetch request
var req = new Request(url);
fetch(req)
.then(function(response) {
return response.json();
})
.then(function(res) {
console.log(res);
// Populating div elements
document.getElementById("stadium_name").innerHTML = (res.articles[1].title);
document.getElementById("stadium_description").innerHTML = (res.articles[1].content);
var articleimg1 = document.getElementById('article-image1');
articleimg1.appendChild(document.createElement('img')).src = (res.articles[1].urlToImage);
...
});
<div class="col-md-3 d-flex align-items-stretch">
<div class="card mt-4 stadiumCard">
<h3 id="stadium_name"></h3>
<div id="article-image1"></div>
<p id="stadium_description">
- Text content here -
</p>
</div>
</div>
// Additional card structures similar to the first example