I’m working on a simple weather app. It shows today and next 4 days weather.
I have two arrays: the first one is WEEK_DAYS
, the second is an array of dom elements to display name of the day.
I want that top dom element always show today’s weather. Second must show tomorrow etc.
________app today should display
-SATURDAY < first dom element
-SUNDAY
-MONDAY
-FRIDAY
-TUESDAY < last dom element
________app tomorrow should display
-SUNDAY < first dom element
-MONDAY
-FRIDAY
-TUESDAY
-WEDNESDAY < last dom element
const WEEK_DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const daysElements = document.querySelectorAll("span.font-light"); // dom elements
const date = new Date();
const today = WEEK_DAYS[date.getDay()]; // date.getDay() returns a number: 0 for sunday, 1 for monday ... 6 for Saturday
I need ideas here on how to achieve that.
[...daysElements].map((d, index) => {
d.innerText = WEEK_DAYS.find((e) => e === today); // of course all dom elements printing "Saturday" (today)
})
3
Answers
You will need to create the respective DOM nodes you want to display using
document.createElement()
. Here in this example I am using a simple unordered list with list items. The get the parent element (e.g. usingquerySelector()
) and append the children to it usingreplaceChildren()
and the nodes are displayed.You’re almost there. Use numbers in calculations, and strings for display:
Also it’s ok to use
forEach
here.Good answers. I thought I’d add mine as an example of a C-like for loop.