Search code examples
javascriptjquerywebapi-design

jquery .append() method producing unwanted result


I'm working on a project using Wikipedia's API. I have been able to successfully load the API's data. However, here is the problem I try to load the API's result into the DOM when an input value is submitted, but each time I try to submit a new value the result is gets appended to the initial result from the first input search.

Here is a fiddle which may show what I mean:

https://jsfiddle.net/aonz929f/1/

    for( var key in data.query.pages){
        //loop through the JSON data 
       }

$("#result").append(htmlContent)/// Then I used the append method to return each returned result to the DOM

Solution

  • You have to clear the already existing html before appending new one, like this:

    $("#result").html("")
    for( var key in data.query.pages){
       $("#result").append(("<p>" + data.query.pages[key].title) + "</p>")
       //etc..        
    }