Reputation:
I am getting animals from a json file randomly and splitting letters into a span and appending it a .wrapper
div.
But when i reload json, new animal appends there and old one doesn't dissappear.
How can i split letter using html()
methtod or how can i reload specific div without refreshing the whole page ?
Click refresh button you see a new animal name appends the div (as we expect).
I am just looking for the solution with using append()
method or not.
function loadJson() {
$.getJSON('https://raw.githubusercontent.com/boennemann/animals/master/words.json', function(data) {
var s = data[Math.floor((Math.random() * data.length))];
for (i = 0; i < s.length; i++) {
var $span = $("<span>", {
class: " letter" + i
}).appendTo(".wrapper");;
$span.append(s[i]);
}
});
}
loadJson();
$("button").click(function() {
loadJson();
});
Upvotes: 2
Views: 2777
Reputation: 337
use $('.classname').empty() before append.. https://jsfiddle.net/9wsjf90r/1/
function loadJson() {
$.getJSON('https://raw.githubusercontent.com/boennemann/animals/master/words.json', function(data) {
var s = data[Math.floor((Math.random() * data.length))];
$('.wrapper').empty();
for (i = 0; i < s.length; i++) {
var $span = $("<span>", {
class: " letter" + i
}).appendTo(".wrapper");;
$span.append(s[i]);
}
});
}
loadJson();
$("button").click(function() {
loadJson();
});
Upvotes: 3