Prepending text to html elements using a Javascript function

I’m trying to use Javascript for formatting the time to a localized format using Intl.DateTimeFormat method.

I have several instances of time strings in 24h format i want to localize in a HTML page, for example:

<span class="timeclass">18:45</span> //and so on..

And i am able to format the time with the following code, which uses a Date object:

            let locale = 'en-US'; // this variable changes, example 'en-UK', etc
            let time = new Date('1971-12-12T18:45');
            console.log(new Intl.DateTimeFormat(locale, { 
              hour: 'numeric',
              minute: 'numeric',
            }).format(time));  //output is "6:45 PM"

As the code shows, i added a dummy date in order for the Date object to be semantically correct. Now, i’m trying to write a function to replace all instances of times contained within timeelem classes:

var locale = 'en-US';
var timeformat = new Intl.DateTimeFormat(locale, { 
    hour: 'numeric',
    minute: 'numeric',
});

timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => { 
timeelements.textContent= timeformat.format(timeelements.textContent);  
 });

But it is not working because it is getting the time in the format 18:45 instead of 1971-12-12T18:45. What is the best way to prepend such dummy date to the string? The date is only relevant for the localization function to work, by the way.

Answer

You can choose any date you want, as long as it is in the correct format. You can do something like this: WORKING DEMO

HTML

<span class="timeclass">18:45</span>
<span class="timeclass">18:15</span>
<span class="timeclass">11:45</span>
<span class="timeclass">02:45</span>
<span class="timeclass">22:45</span>
<span class="timeclass">23:45</span>
<span class="timeclass">18:00</span>

JAVASCRIPT

timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
  console.log("elem ", element.innerHTML);
  // Append any date. Use your birthday.
  const timeString12hr = new Date('1970-01-01T' + element.innerHTML + 'Z')
    .toLocaleTimeString({}, {
      timeZone: 'UTC',
      hour12: true,
      hour: 'numeric',
      minute: 'numeric'
    });
    
  element.innerHTML = timeString12hr
});

————————UPDATED————————

var locale = "en-US";

var timeformat = new Intl.DateTimeFormat(locale, {
  hour: 'numeric',
  minute: 'numeric',
});

timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
  console.log("elem ", element.innerHTML);
    const timeString12hr = new Date('1970-01-01T' + element.innerHTML + 'Z');
  element.innerHTML = timeformat.format(timeString12hr)
});