How do I clear all options in a dropdown box?

2020-01-24 06:44发布

My code works in IE but breaks in Safari, Firefox, and Opera. (big surprise)

document.getElementById("DropList").options.length=0;

After searching, I've learned that it's the length=0 that it doesn't like.
I've tried ...options=null and var clear=0; ...length=clear with the same result.

I am doing this to multiple objects at a time, so I am looking for some lightweight JS code.

27条回答
何必那么认真
2楼-- · 2020-01-24 07:19

Using JQuery is a prettier, shorter & smarter way to do it!

$('#selection_box_id').empty();
查看更多
Ridiculous、
3楼-- · 2020-01-24 07:20

Go reverse. Reason is size decreases after each remove.

for (i = (len-1); i > -1; i--) {
    document.getElementById("elementId").remove(i);
}
查看更多
狗以群分
4楼-- · 2020-01-24 07:22

I'd like to point out that the problem in the original question is not relevant today anymore. And there is even shorter version of that solution:

selectElement.length = 0;

I've tested that both versions work in Firefox 52, Chrome 49, Opera 36, Safari 5.1, IE 11, Edge 18, latest versions of Chrome, Firefox, Samsung Internet and UC Browser on Android, Safari on iPhone 6S, Android 4.2.2 stock browser. I think it is safe to conclude that it's absolutely compatible with whatever device there is right now, so I recommend this approach.

查看更多
登录 后发表回答