0

I have some code that builds elements of a list on a sidebar. If a button is clicked I want to clear the list and repopulate it with new results. Right now the information just adds to the list. I would like to clear all of the items in the list so I can readd them.

function buildLocationList(data) {
    for (i = 0; i < data.locations.length; i++) {
      var currentFeature = data.locations[i];
      var prop = currentFeature.locations;


      var listings = document.getElementById('listings');
      var listing = listings.appendChild(document.createElement('div'));

      listing.className = 'item';
      listing.id = "listing-" + i;        

      var link = listing.appendChild(document.createElement('a'));
      link.href = '#';
      link.className = 'title';
      link.dataPosition = i;
      link.innerHTML = '<b>' + currentFeature.company; + '</b>'

      var address = listing.appendChild(document.createElement('div'));
      address.innerHTML = currentFeature.address;

      var csz = listing.appendChild(document.createElement('div'));
      csz.innerHTML = currentFeature.csz;    

      /*var hours = listing.appendChild(document.createElement('div'));
      hours.innerHTML = currentFeature.hours[0].days + ': ' + currentFeature.hours[0].hours;
      hours.style.color = 'gray'; */ 

      link.addEventListener('click', function(e){
        // Update the currentFeature to the store associated with the clicked link
        var clickedListing = data.locations[this.dataPosition];

        // 1. Fly to the point
        flyToStore(clickedListing);

        // 2. Close all other popups and display popup for clicked store
        createPopUp(clickedListing);

        // 3. Highlight listing in sidebar (and remove highlight for all other listings)
        var activeItem = document.getElementsByClassName('active');

        if (activeItem[0]) {
           activeItem[0].classList.remove('active');
        }
        this.parentNode.classList.add('active');

      });
    }
  }
blg2
  • 355
  • 6
  • 23
  • 2
    Possible duplicate of [How do I clear the content of a div using JavaScript?](https://stackoverflow.com/questions/3450593/how-do-i-clear-the-content-of-a-div-using-javascript) – Heretic Monkey Jan 21 '19 at 22:02
  • Potentially better duplicate: https://stackoverflow.com/q/3955229/215552 – Heretic Monkey Jan 21 '19 at 22:03

1 Answers1

1

For your particular case, add this before you do anything else:

document.getElementById('listings').innerHTML = "";
Word Rearranger
  • 1,306
  • 1
  • 16
  • 25