开发者

removing all option of dropdown box in javascript

How can i dynam开发者_StackOverflow中文版ically remove all options of a drop down box in javascript?


document.getElementById('id').options.length = 0;

or

document.getElementById('id').innerHTML = "";


var select = document.getElementById('yourSelectBox');

while (select.firstChild) {
    select.removeChild(select.firstChild);
}


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);
}


<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>


Its very easy using JavaScript and DOM:

while (selectBox.firstChild)
    selectBox.removeChild(selectBox.firstChild);


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;
}


There is simple and elegant way to do this:

for(var o of document.querySelectorAll('#id > option')) {
  o.remove()
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜