NZMAI NZMAI - 4 months ago 11
Javascript Question

Remove preveous appended list items before clicking tthe button

I'm using Wikipedia API for my project. When i click a button to show a quote my code dynamically appends articles from wikipedia to ul related to the particular author. However when i click the button new li of others authors added to ul, so old articles (li) not removed. I have tried to put code in for loop before append to ul but then when i click the button it adds only one article, instead of all.

My code is:

var getWikiAuthorBio = function(author) {
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=' + author + '&format=json&callback=wikiCalback'

//////////////
//Wiki request
/////////////
var wikirequest = function() {
$.ajax({
url:url,
dataType: 'jsonp',
success: function(wikiData) {

// Fetch the biographical information
var bioName = wikiData[2][0];

// Check if instead of bio there is a phrase "The article may refer to...." if so then change indices
if (bioName.indexOf('may refer to') >= 0) {
bioName = wikiData[2][1];
} else {
var bioName = wikiData[2][0];
}

var wikiArcticles = wikiData[1];
var wikiArticlesShortInfo = wikiData[2]
console.log(wikiArticlesShortInfo);

for (var i=0; i < wikiArcticles.length; i++) {

console.log("Each article " + wikiArcticles[i]);
domCache.$wikiArticlesList.append('<li class="articleItem">'+ wikiArcticles[i]+ '</li>');
}

// Short biography
console.log(bioName);
console.log(wikiArcticles);
console.log(url);

domCache.$bioDiv.text(bioName);



} // end of success
});
}// wikirequest

wikirequest();

}


Link to Codepen

Answer

You can also use the jQuery empty function.

domCache.$wikiArticlesList.empty();

Put in before the for-loop