I’m currently a web developer boot camp student and I am working on a project. I know there is a way to simplify this function but I can’t seem to grasp it. What is the way to simplify this entire thing into a for loop so I don’t have to do this to every element? I am calling a weather API and applying them to the HTMl. Also, I am using the querySelector as for some reason, JQuery doesn’t want to allow me to use the $.
HTML
<div class="row bottom">
<div class="col"><span class="subtitle">-Temperature-</span></div>
<div class="col">
<div class="row" id="date1">Sun</div>
<div class="row data" id="date1Temp"><b>-4°</b></div>
</div>
<div class="col">
<div class="row" id="date2">Mon</div>
<div class="row data" id="date2Temp"><b>-5°</b></div>
</div>
<div class="col">
<div class="row" id="date3">Tue</div>
<div class="row data" id="date3Temp"><b>-10°</b></div>
</div>
<div class="col">
<div class="row" id="date4">Wed</div>
<div class="row data" id="date4Temp"><b>-4°</b></div>
</div>
<div class="col">
<div class="row" id="date5">Thu</div>
<div class="row data" id="date5Temp"><b>-2°</b></div>
</div>
<div class="col">
<hr />
</div>
</div>
JS
let fiveDayWeather = function (weatherValue) {
const date1 = document.querySelector("#date1");
const date2 = document.querySelector("#date2");
const date3 = document.querySelector("#date3");
const date4 = document.querySelector("#date4");
const date5 = document.querySelector("#date5");
const date1Temp = document.querySelector("#date1Temp");
const date2Temp = document.querySelector("#date2Temp");
const date3Temp = document.querySelector("#date3Temp");
const date4Temp = document.querySelector("#date4Temp");
const date5Temp = document.querySelector("#date5Temp");
let todaysMonth = dayjs().$M;
let tomorrow = dayjs().$D + 1;
let twoDaysAfter = dayjs().$D + 2;
let threeDaysAfter = dayjs().$D + 3;
let fourDaysAfter = dayjs().$D + 4;
let fiveDaysAfter = dayjs().$D + 5;
date1.innerText = `${todaysMonth}/${tomorrow}`;
date1Temp.innerText = weatherValue.list[1].main.temp + "u00B0 F";
date2.innerText = `${todaysMonth}/${twoDaysAfter}`;
date2Temp.innerText = weatherValue.list[2].main.temp + "u00B0 F";
date3.innerText = `${todaysMonth}/${threeDaysAfter}`;
date3Temp.innerText = weatherValue.list[3].main.temp + "u00B0 F";
date4.innerText = `${todaysMonth}/${fourDaysAfter}`;
date4Temp.innerText = weatherValue.list[4].main.temp + "u00B0 F";
date5.innerText = `${todaysMonth}/${fiveDaysAfter}`;
date5Temp.innerText = weatherValue.list[5].main.temp + "u00B0 F";
3
Answers
Here you go with some comments:
To DRY up your code you can amend your code to remove the incremental
id
attributes. Instead, you can use commonclass
attributes to create common structures in your HTML which you can use DOM traversal methods, such asclosest()
, to find related content, something like this:Something like this should work: