-2

I am trying to loop over a DOM element and add aria-labels to them.

  const dayAriaLabels = {
    Mo: 'Monday',
    Tu: 'Tuesday',
    We: 'Wednesday',
    Th: 'Thursday',
    Fr: 'Friday',
    Sa: 'Saturday',
    Su: 'Sunday',
  };

  setTimeout(() => {
    const selectDomElement = document.querySelectorAll('.MuiPickersCalendarHeader-dayLabel');
    if (!isEmpty(selectDomElement)) {
      selectDomElement.forEach((label) => {
        Object.entries(dayAriaLabels).forEach(([key, value]) => {
          label.setAttribute('aria-label', value);
        });
      });
    }
  }, 100);

However when I inspect the dom element this happens enter image description here

As you can see only Sunday is added? What is happening here? why cant I add all of the days from the object?

Broken Mind
  • 511
  • 3
  • 8
  • 22
  • Try using your browser’s [debug capabilities](//ali-dev.medium.com/how-to-easily-debug-in-javascript-5bac70f94f1a). See [What is a debugger and how can it help me diagnose problems?](/q/25385173/4642212). It’ll tell you immediately what’s going on. Find out what `label` is and what `value` is in the inner `forEach` callback. – Sebastian Simon Dec 22 '22 at 13:42
  • Well you have two forEach when you should only have one – Lk77 Dec 22 '22 at 13:42
  • 2
    For *each* DOM element, you loop through *each* day label, and *repeatedly* set the label on the current DOM element. So yeah, for each DOM element, only the last label you iterate over actually remains set, as it can only hold one label at a time. And you do this for each DOM element in turn… – deceze Dec 22 '22 at 13:42

1 Answers1

0

You should only have one forEach like so :

  const dayAriaLabels = {
    Mo: 'Monday',
    Tu: 'Tuesday',
    We: 'Wednesday',
    Th: 'Thursday',
    Fr: 'Friday',
    Sa: 'Saturday',
    Su: 'Sunday',
  };

  setTimeout(() => {
    const selectDomElement = document.querySelectorAll('.MuiPickersCalendarHeader-dayLabel');
    if (!isEmpty(selectDomElement)) {
      selectDomElement.forEach((label) => {
        label.setAttribute('aria-label', dayAriaLabels[label.innerText]);
      });
    }
  }, 100);

And not loop over all days each time

Lk77
  • 2,203
  • 1
  • 10
  • 15