I am new to js and I am trying to loop through elements by class name and make a change to the element's textcontent using javascript. The following is what I have so far, but this does not work.
<script type="text/javascript">
function dformat(i) {
var hasDate = document.getElementsByClassName("dformat")[i].textContent.trim().includes("/");
if(hasDate === false) {
window.setTimeout(dformat, 100); /* this checks the flag every 100 milliseconds*/
} else {
dateString = document.getElementsByClassName("dformat")[i].textContent.trim();
const options = { year: 'numeric', month: 'short', day: 'numeric' };
let dateArr = dateString.split("/");
var sMonth = dateArr[0];
var sDay = dateArr[1];
var sYear = dateArr[2];
let newDateString = sYear + "/" + sMonth + "/" + sDay
let newDate = new Date(newDateString);
document.getElementsByClassName("dformat")[i].textContent=newDate.toLocaleDateString('en-us', options);
}
}
var ditems = document.getElementsByClassName("dformat");
for (var i = 0; i < ditems.length; i++) {
dformat(i);
}
</script>
The following is an example of one of the elements
<span class="dformat">26/06/1992</span>
The expected output would be to have changed text on each of the elements with class dformat
Update: I tried the same function with getelementbyid on a single element (i.e without a for loop) and got the expected result. I have trouble doing the same on a set of elements by classname instead of a single element by id.