I am trying to display new list of shuffled array on onclick but my code is just appending the new shuffled array below the previous list. My code is:
function shuffleArray() {
var array = ['1','2','3','4'];
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
for (i=0;i<array.length;i++) {
var span = document.createElement('span');
span.innerHTML = array[i];
span.onclick = shuffleArray; //calls the same function
var div = document.createElement('div');
div.appendChild(span);
document.body.appendChild(div);
}
}
Current output:
2
1
4 // if I click here then results gets appended below
3
3
2
4
1 // if I click here then results gets appended below
2
1
4
3 // and so on
Desired output: I want the page content to get updated with new array elements, each time I click some array element.
appendfunction, thenonclickdoesn't works.wrapping_div.innerHTML='';. Either that, or store each div you append to an array and then, when you need to remove them, step through the array usingbody.removeChild(div);.