Why is my for-loop generating each response multiple times?

Viewed 64

I am trying to create a for loop that generates the date for the next 5 days and prints them in an empty h6 element, but instead of generating 5 dates one time, it is generating 5 dates five times, as shown in the console log. (I know moment.js isn't recommended anymore, this is just for a project)

screenshot of the console log result

This is my code:

for (var x = 1; x <= 5; x++){
  $(".future-date").text(moment().add([x], "d").format("(MM/DD/YYYY)"));
  console.log($(".future-date").text());
}

The result is that all h6 elements display the 5th date.

It should look like this, with 5 consecutive dates

Instead, they are all showing the last date.

What am I missing?

2 Answers

You can use eq to access a single element in a jQuery collection.

$(".future-date").eq(x - 1).text(moment().add([x], "d").format("(MM/DD/YYYY)"));

Alternatively, you can use .each.

$(".future-date").each(function(i){
  $(this).text(moment().add([i + 1], "d").format("(MM/DD/YYYY)"));
});

Use text(function) instead. This will iterate over all the matching elements and expose the index of each element within the collection and return calculated value for each element instance

When you do $(selector).text(string) internally it loops over each matching selector and does the same to each one. So your loop changes all elements to the same value each iteration and you end up just seeing the last one in all of them

$(".future-date").text(function(i) {
  return moment().add([i + 1], "d").format("(MM/DD/YYYY)");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

<h4 class="future-date"></h4>
<h4 class="future-date"></h4>
<h4 class="future-date"></h4>
<h4 class="future-date"></h4>

Related