Skip to content

Why is my .empty() not emptying the parent element?

I cannot get the jQuery empty method to work on my appended HTML elements. It’s quite a simple problem seemingly, but it has me beat.

I’ve tried moving the empty method around in the code but I still cannot get it to empty.

Edit: It will not let me edit this unless there is more text so here is some more text.

My jQuery/JavaScript:

// Declares blank arrays
let monthHolidayName = [];
let monthHolidayDescription = [];
let monthHolidayDay = [];
let monthHolidayMonth = [];
let monthHolidayIsoDate = [];
              
// On change pushes the arrays with the current months data
$('#monthSelect').change(function(){
          
  var selectedMonth = $('#monthSelect').val();
  var numSelectedMonth = parseInt(selectedMonth) + 1;

  for(i = 0; i < result['data']['holidays'].length; i++){
    var holidayMonth = result['data']['holidays'][i]['date']['datetime']['month'];
    if(holidayMonth === numSelectedMonth){
      // console.log((result['data']['holidays'][i]));
      monthHolidayName.push(result['data']['holidays'][i]['name']);
      monthHolidayDescription.push(result['data']['holidays'][i]['description']);
      monthHolidayDay.push(result['data']['holidays'][i]['date']['datetime']['day']);
      monthHolidayMonth.push(result['data']['holidays'][i]['date']['datetime']['month']);
      monthHolidayIsoDate.push(result['data']['holidays'][i]['date']['iso']);
    }
  }

  // Empties the #holidays element <--------------------
  $("#holidays").empty();
  
  // Appends the data to the modal
  for(i = 0; i < monthHolidayName.length; i++){
    var holidayName = monthHolidayName[i];
    var holidayDescription = monthHolidayDescription[i];
    var holidayDay = monthHolidayDay[i];
    var holidayDayMonth = monthHolidayMonth[i];
    var holidayIsoDate = monthHolidayIsoDate[i];

    var dateParsed = Date.parse(`${holidayDay} ${holidayDayMonth}`).toString("MMMM dS");
    // Appends elements to #holidays with the data         
    $("#holidays").append(`<div class="list-group-item list-group-item-action"><div style="text-decoration: underline; text-align: center;">${holidayName}</div><div style="text-align: center">${holidayDescription}</div><small class="text-muted">${holidayIsoDate}</small></div>`);
  }          
});

My HTML code:

 <!-- Calendar Modal -->
<div class="container">
  <div class="row">
    <div class="col-md-12">
        <div class="modal fade " id="calendar-modal">
          <div class="modal-dialog">
            <div class="modal-content">
               
              <div class="modal-header"> 
                  <h1 id="modalTitle">Holidays</h1>
                  <button type="button" class="close btn btn-secondary" data-bs-dismiss="modal" >&times;</button>
              </div>
              <!-- This is the body section of our modal overlay --> 
               <div class="modal-body" id="modalBody">
                <div class="btn-group dropright">
                  <select class="form-select form-select-sm mb-3" id="monthSelect"> 

                  </select>
                </div>
                <div class="list-group">
                  <button type="button" class="list-group-item list-group-item-action active" id="holidayTitle">
                    Holidays in <span id="currentMonth"></span>
                  </button>
                  <span id="holidays">
                  </span>
                  
                </div>               
              </div>
               <!-- This is the footer section of our modal overlay  -->
              <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" >Close</button>
              </div>
            </div>
          </div>
        </div>
     </div>
  </div>
</div> 

Answer

It seems that you want to both append new data to your existing data while also deleting the old data. Your code is constantly referencing append, which implies that you want to keep the previous data, but your question asks about how to clear the holidays div, and then add the new holiday.

Answering your question, we don’t need an array if we’re always deleting the previous holiday information, instead we can use a JavaScript Object to hold the information. The other portion that you’ll notice I changed is I took out the for loop you had. Since we have a single holiday, we don’t need to iterate through an array. The following code should show how to work with a single holiday in an Object. Note that I did not change the HTML

// Declare an object with our empty parameters:
let holiday = {
  name: "",
  description: "",
  day: "",
  month: "",
  isoDate: ""
};
          
// On change pushes the arrays with the current months data
$('#monthSelect').change(function(){
      
  var selectedMonth = $('#monthSelect').val();
  var numSelectedMonth = parseInt(selectedMonth) + 1;

  for(i = 0; i < result['data']['holidays'].length; i++){
    var holidayMonth = result['data']['holidays'][i]['date']['datetime']['month'];
    if(holidayMonth === numSelectedMonth){
      // console.log((result['data']['holidays'][i]));

      // Using object setter notation to change each key:
      holiday.name = result['data']['holidays'][i]['name'];
      holiday.description = result['data']['holidays'][i]['description'];
      holiday.day = result['data']['holidays'][i]['date']['datetime']['day'];
      holiday.month = result['data']['holidays'][i]['date']['datetime']['month'];
      holiday.isoDate = result['data']['holidays'][i]['date']['iso'];
    }
  }

  // Empties the #holidays element <--------------------
  $("#holidays").empty();

  var dateParsed = Date.parse(`${holiday.day} ${holiday.month}`).toString("MMMM dS");
  // Appends elements to #holidays with the data         
  $("#holidays").append(`<div class="list-group-item list-group-item-action"><div style="text-decoration: underline; text-align: center;">${holiday.name}</div><div style="text-align: center">${holiday.description}</div><small class="text-muted">${holiday.isoDate}</small></div>`);
});