I've written this JS code, but I feel like there could be a better way to achieve the same results. Currently, I have 5 different functions that are quite similar, and I'm looking for a more efficient solution with less code repetition:
HTML:
<div class="news-wrap margin-top-div">
<div class="news-btn-container-flex">
<div class="news-btn-div current" data-tab="1" onclick="req(1)">1</div>
<div class="news-btn-div" data-tab="2" onclick="req(2)">2</div>
<div class="news-btn-div" data-tab="3" onclick="req(3)">3</div>
<div class="news-btn-div" data-tab="4" onclick="req(4)">4</div>
<div class="news-btn-div" data-tab="5" onclick="req(5)">5</div>
</div>
<div class="news-content-container-flex">
<div class="news-title">
<span id="newsTitle">
</span>
</div>
<div id="content-news">
</div>
</div>
</div>
JS:
function req(num) {
fetch(`https://jsonplaceholder.typicode.com/posts/${num}`)
.then(function (res) {return res.json()})
.then(function (json) {
var title = json.title;
var body = "";
var i = 0;
while (i <= 5) {
body += json.body;
i++;
}
document.getElementById("newsTitle").innerHTML = title;
document.getElementById("content-news").innerHTML = body;
});
}
req(1);
req(2);
req(3);
req(4);
req(5);
It seems like there is too much repetitive code in my current approach. I would like to streamline it while also ensuring compatibility with older browsers by avoiding using new features like ES6. Any suggestions on how I can improve this?