最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to clear HTML data list current options? - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

4 Answers 4

Reset to default 12

In 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

发布评论

评论列表(0)

  1. 暂无评论