How to clear HTML data list current options?
Asked Answered
D

4

5

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

Deepset answered 14/6, 2017 at 19:3 Comment(1)
do you have plunker for this ?Moonrise
A
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 = '';

Adames answered 14/6, 2017 at 19:6 Comment(0)
O
1

I like this one. Seems the cleanest I could find, but it is jQuery not vanilla JS DOM.

$('#schoolNameList').empty();
Osteoclasis answered 26/7, 2021 at 3:25 Comment(0)
D
1

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);
}
Dori answered 26/5, 2022 at 8:11 Comment(1)
I voted +1 but finally, when I change my input, it not the replaceWith (under ubuntu 22 with firefox 117) doesn't work !Bitstock
B
0

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

Bitstock answered 22/8, 2023 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.