removing all option of dropdown box in javascript

后端 未结 7 1733
自闭症患者
自闭症患者 2021-02-01 04:21

How can i dynamically remove all options of a drop down box in javascript?

相关标签:
7条回答
  • 2021-02-01 05:02

    Setting the length to 0 is probably the best way, but you can also do this:

    var mySelect = document.getElementById("select");
    var len = mySelect.length;
    for (var i = 0; i < len; i++) {
        mySelect.remove(0);
    }
    
    0 讨论(0)
  • 2021-02-01 05:02

    Its very easy using JavaScript and DOM:

    while (selectBox.firstChild)
        selectBox.removeChild(selectBox.firstChild);
    
    0 讨论(0)
  • 2021-02-01 05:08
    document.getElementById('id').options.length = 0;
    

    or

    document.getElementById('id').innerHTML = "";
    
    0 讨论(0)
  • 2021-02-01 05:11

    The fastest solution I was able to find is the following code (taken from this article):

    // Fast javascript function to clear all the options in an HTML select element
    // Provide the id of the select element
    // References to the old <select> object will become invalidated!
    // This function returns a reference to the new select object.
    function ClearOptionsFast(id)
    {
        var selectObj = document.getElementById(id);
        var selectParentNode = selectObj.parentNode;
        var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
        selectParentNode.replaceChild(newSelectObj, selectObj);
        return newSelectObj;
    }
    
    0 讨论(0)
  • 2021-02-01 05:15
    <select id="thing"><option>fdsjl</option></select>
    <script>
    var el = document.getElementById('thing');
    el.innerHTML = '';
    
    // or this
    
    while ( el.firstChild ) {
       el.removeChild( el.firstChild )
    }
    </script>
    
    0 讨论(0)
  • 2021-02-01 05:17
    var select = document.getElementById('yourSelectBox');
    
    while (select.firstChild) {
        select.removeChild(select.firstChild);
    }
    
    0 讨论(0)
提交回复
热议问题