I am writing an dynamic data list. However, when I tried to update the list, the previous didn't clear. Are there any solutions?
Here is my code
function loadDataList(selectedSchoolName)
{
var options = '';
//document.getElementById('schoolNameList').remove();
for(var i = 0; i < selectedSchoolName.length; i++)
{
options += '<option value="'+ selectedSchoolName[i] +'" >';
}
document.getElementById('schoolNameList').innerHTML = options;
}
Thank You
I am writing an dynamic data list. However, when I tried to update the list, the previous didn't clear. Are there any solutions?
Here is my code
function loadDataList(selectedSchoolName)
{
var options = '';
//document.getElementById('schoolNameList').remove();
for(var i = 0; i < selectedSchoolName.length; i++)
{
options += '<option value="'+ selectedSchoolName[i] +'" >';
}
document.getElementById('schoolNameList').innerHTML = options;
}
Thank You
Share Improve this question asked Jun 14, 2017 at 19:03 Siu HarrySiu Harry 511 gold badge1 silver badge2 bronze badges 1- do you have plunker for this ? – Binary Brackets Commented Jun 14, 2017 at 19:05
4 Answers
Reset to default 12In this instance, you don't want to remove schoolNameList
itself; you want to remove the children of that list (the list items). There are a few ways to do this, but this one should work:
document.getElementById('schoolNameList').innerHTML = '';
I like this one. Seems the cleanest I could find, but it is jQuery not vanilla JS DOM.
$('#schoolNameList').empty();
Simpler way and in Vanilla JS to do is by using the node.replaceWith() method.
Removing all childs in a loop can be a costly DOM operation.
Example:
const node = document.getElementById("schoolNameList");
if(node.hasChildNodes) {
const newNodeToReplace = node.cloneNode(false); //false: because we don't want to deep clone it
node.replaceWith(newNodeToReplace);
}
similar issue, I first test @Shrey Kumar solution.
At first tests, it seems to work (no more duplicate entries) but if I change my input to another, the replaceWith
doesn't work.
I test it too under console with no more success.
So I finally use myDataList.replaceChildren()
that remove datalist children just before create new options and append its and it works fine !
replaceChildren doc