Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear HTML data list current options?

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

like image 889
Siu Harry Avatar asked Dec 23 '22 17:12

Siu Harry


2 Answers

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 = '';

like image 178
Ben Schroeder Avatar answered Dec 31 '22 14:12

Ben Schroeder


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

$('#schoolNameList').empty();
like image 32
Craig Conover Avatar answered Dec 31 '22 14:12

Craig Conover