Naser Naser - 3 months ago 8
jQuery Question

How to replace elements of array instead of joining them on function call in jquery?

var currentYear;
while ( i < months.length) {
annualMonths.push("<h4>" + months[i] + "</h4><span id='monthDates'><ul class='datum monthselection'>" + daysInMonth(i, currentYear) + "</ul></span><br>");
//$(".monthName").replaceWith("<h4>" + months[i] + "</h4><span id='monthDates'><ul class='datum monthselection'>" + daysInMonth(i, currentYear) + "</ul></span><br>");
i++;
}
$("#calendar .currentYear .monthName").html(annualMonths);
i =1;


This function display all numbered days from all months of a year.

The problem is that I would like each time I make a call to that function to replace existing data instead of join at the end of the DOM.

How is this possible?

Answer

You can remove all child nodes of the set of matched elements from the DOM using empty() method like:

function displayCalendar(currentYear) {
  var i = 1;
  var currentYear;

  // Clear the array before processing again
  annualMonths = [];

  while (i < months.length) {
    annualMonths.push("<h4>" + months[i] + "</h4><span id='monthDates'><ul class='datum monthselection'>" + daysInMonth(i, currentYear) + "</ul></span><br>");
    i++;
  }

  $("#calendar .currentYear .monthName").empty().html(annualMonths);
  i = 1;
}