How to bind every day of a week dynamically to every h1 in HTML

Tags: ,



Hi any idea how to bind every day of a week to every h1 in a way the first h1 shows today, and the next h1 shows tomorrow and the 7th h1 shows the 7th day from toady ? I did this my max was I can only make all of them show toady.. thanks

function currentdaychange() {

  let weekday = ['Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday'
    ]
    [new Date().getDay()];

  console.log(weekday)

  let items = document.querySelectorAll('.currentday');

  document.querySelector('.currentday').innerHTML = weekday;

  for (var i = 0; i < items.length; i++) {
    items[i].innerHTML = weekday;
  }
  requestAnimationFrame(currentdaychange);
}

currentdaychange();
<h1 class=currentday></h1>
<h1 class=currentday></h1>
<h1 class=currentday></h1>
<h1 class=currentday></h1>
<h1 class=currentday></h1>
<h1 class=currentday></h1>
<h1 class=currentday></h1>

Answer

You can retrieve a localized day of the week using Date.prototype.toLocaleDateString and passing in the option { weekday: 'long' }.

const formatDayOfWeek = date =>
  date.toLocaleDateString('en-US', { weekday: 'long' });

const incrementDay = date => {
  date.setDate(date.getDate() + 1);
  return date;
};

const currentDayChange = () => {
  const now = new Date();
  [...document.querySelectorAll('.day-of-week')].forEach(day => {
    day.textContent = formatDayOfWeek(now);
    incrementDay(now);
  });
}

currentDayChange();
h1 {
  font-size: smaller;
}
<h1 class="day-of-week current-day"></h1>
<h1 class="day-of-week"></h1>
<h1 class="day-of-week"></h1>
<h1 class="day-of-week"></h1>
<h1 class="day-of-week"></h1>
<h1 class="day-of-week"></h1>
<h1 class="day-of-week"></h1>


Source: stackoverflow