Javascript 删除javascript中下拉框的所有选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4618763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
removing all option of dropdown box in javascript
提问by akshay
How can i dynamically remove all options of a drop down box in javascript?
如何动态删除javascript中下拉框的所有选项?
回答by hunter
document.getElementById('id').options.length = 0;
or
或者
document.getElementById('id').innerHTML = "";
回答by lonesomeday
var select = document.getElementById('yourSelectBox');
while (select.firstChild) {
select.removeChild(select.firstChild);
}
回答by pushkin
Setting the length
to 0 is probably the best way, but you can also do this:
将 设置length
为 0 可能是最好的方法,但您也可以这样做:
var mySelect = document.getElementById("select");
var len = mySelect.length;
for (var i = 0; i < len; i++) {
mySelect.remove(0);
}
回答by Alex
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;
}
回答by Piotr
There is simple and elegant way to do this:
有一种简单而优雅的方法可以做到这一点:
for(var o of document.querySelectorAll('#id > option')) {
o.remove()
}
回答by meder omuraliev
<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>
回答by Guss
Its very easy using JavaScript and DOM:
使用 JavaScript 和 DOM 非常容易:
while (selectBox.firstChild)
selectBox.removeChild(selectBox.firstChild);