246

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.

Kara
  • 6,115
  • 16
  • 50
  • 57
Kirt
  • 2,553
  • 2
  • 17
  • 11
  • To **destroy** all options (!?), and about reset the browser's history of selected options after refresh page, to use the HTML's ` – Peter Krauss Aug 14 '19 at 08:49

31 Answers31

371

To remove the options of an HTML element of select, you can utilize the remove() method:

function removeOptions(selectElement) {
   var i, L = selectElement.options.length - 1;
   for(i = L; i >= 0; i--) {
      selectElement.remove(i);
   }
}

// using the function:
removeOptions(document.getElementById('DropList'));

It's important to remove the options backwards; as the remove() method rearranges the options collection. This way, it's guaranteed that the element to be removed still exists!

someOne
  • 1,975
  • 2
  • 14
  • 20
Fabiano
  • 5,001
  • 2
  • 28
  • 31
  • 10
    cheers for that @Fabiano, this actually removes the items as opposed to other suggestions. – Constanta Feb 18 '14 at 15:19
  • 4
    the key here is the backwards traversal of the selectbox.options I think....this solution failed when I tried forwards traversal – scottysseus Jan 26 '16 at 14:46
  • 7
    Yes, it will fail because the remove() method will rearrange the array. Doing it backwards will guarantee that the element to be removed will exist. – Fabiano Jan 26 '16 at 14:54
  • 1
    Adding selectbox.options.length = 0; in the end of definition might make it perfect in all browsers. – omkar sirra Sep 22 '17 at 07:52
  • 5
    Simple code is while(selectEl.options.length) selectEl.options.remove(0) – MiF Nov 17 '17 at 12:59
  • 1
    One more option is `selectEl.innerHTML = "";` – Galley Oct 21 '22 at 15:21
178

If you wish to have a lightweight script, then go for jQuery. In jQuery, the solution for removing all options will be like:

$("#droplist").empty();
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
Kangkan
  • 15,267
  • 10
  • 70
  • 113
  • 68
    I'd argue that the very act of adding jQuery is the opposite of "lightweight" when `for (a in select.options) { select.options.remove(0); }` does the work just fine. – Artog Feb 11 '14 at 11:06
  • 12
    It depends on the context. In a web application, the readability a hundred lines of `$("#droplist").empty();` type code compared to thousands of lines of vanilla JS make it well worth the addition of jQuery. If we're talking markup/cosmetics for a simple webpage, you're 100% correct. – Half_Duplex Apr 05 '16 at 15:56
  • 7
    @AdamIngmansson I find it puzzling when people denigrate the use of JQuery. I'd use a method like this on the assumption that the engineers behind JQ have done all sorts of tests to find the best, fastest and above all most reliable means of doing a given (utility) task. The point of JQ (or any good library) is to take on the mundane tasks so you can concentrate on the interesting things. – mike rodent Aug 08 '17 at 06:51
  • 5
    @mikerodent I have no doubt that the function itself is of top quality and performance. But loading a 86kb (the compressed lib of version 3.2.1) file just for that little function is not 'lightweight' :) Of course, if you have use of many of the other functionality, the it will be worth using jQuery. It's a very good library – Artog Aug 08 '17 at 07:00
  • 1
    @AdamIngmansson Fair enough! But I take it you're aware that the JQ min.js file is used so often it is very often found in a browser's cache. To such an extent that there's probably a good argument for saying "always use JQ and regard NOT using it as part of an optimisation stage, IF this really proves necessary". It may possibly indeed prove necessary in certain contexts (phone apps, etc.) ... this is beyond my paltry JS knowledge. – mike rodent Aug 09 '17 at 06:40
  • Since I use jQuery in pretty much every JS project I've ever built, this was my go-to one-line answer. – Mike Dailor Oct 24 '22 at 13:31
146

Probably, not the cleanest solution, but it is definitely simpler than removing one-by-one:

document.getElementById("DropList").innerHTML = "";
Dmitry Shintyakov
  • 1,664
  • 1
  • 11
  • 12
  • I usually avoid innertHTML like the plague. But this makes things so much simpler that I actually like it. – petersaints Jun 26 '19 at 11:41
  • 1
    I couldn't get this to work. Not sure why is doesn't clear the select options this way. – MikaelL Feb 10 '20 at 15:26
  • 1
    @MikaelL, it's useful if you add what browser it happens in. And its version, if you can remember. – user May 22 '20 at 04:47
98

This is the best way :

function (comboBox) {
    while (comboBox.options.length > 0) {                
        comboBox.remove(0);
    }        
}
t j
  • 7,026
  • 12
  • 46
  • 66
Rodrigo Longo
  • 1,369
  • 10
  • 15
65

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.

user
  • 23,260
  • 9
  • 113
  • 101
53

You can use the following to clear all the elements.

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = length-1; i >= 0; i--) {
  select.options[i] = null;
}
Tal Z
  • 3,170
  • 17
  • 30
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    It still crashed when i try the above JS...probably some other conflicting code. I hadn't considered jQuery. I think that's just what I'm looking for...but maybe to remove the whole option child: $("select[id$=DropList] > option").remove(); – Kirt Jul 29 '10 at 18:19
  • 18
    MooTools also has `empty()`, so you would do `$("DropList").empty();` – Brian Koser Sep 12 '12 at 19:37
  • 53
    This seems like a bad idea - setting the items to null is not the same as removing them. –  Jun 04 '13 at 17:36
  • 9
    It also dosen't work as excpected. When i use that code it leaves one object in dropdown. – gabrjan Jul 19 '13 at 10:09
  • 9
    This code might crash. The safest way to run the loop in reverse. – Kangkan May 14 '14 at 05:41
  • 21
    Check the other answers for a better way to do this. – Tim Cavanaugh Aug 04 '14 at 18:35
  • 1
    This code will fail as we are trying to remove the options from index 0. The for loop should be run in reverse order starting from the (length-1) to 0. – Kangkan Sep 04 '14 at 05:26
  • 7
    This is a WRONG IMPLEMENTATION AND SHOULD NOT BE THE ANSWER. since you are clearing the array the loop should run from (length-1) to 0. – Sathesh Feb 12 '15 at 23:19
  • 3
    right, it should be rather: for (i = length-1; i >= 0 ; i--) { – Picard Oct 17 '16 at 08:24
  • 2
    This answer is wrong. I have used it without thinking and noticed that the select box didn't empty. Only half. Called again. Again only half. I tried to post an edit to correct the code but it was rejected. This answer is wrong. What to do? – NilsB Dec 11 '16 at 09:33
  • This removes options instead of deselecting them. – Davy Jun 01 '17 at 19:41
  • 1
    select.options.length = 0 will do – Dinesh K Jun 20 '18 at 05:39
51

This is a short way:

document.getElementById('mySelect').innerText = null;

One line, no for, no JQuery, simple.

Ani Menon
  • 27,209
  • 16
  • 105
  • 126
Firemen26
  • 1,025
  • 12
  • 21
  • Not the shortest, see [my answer](https://stackoverflow.com/a/55897038/3075942) below. – user Jun 27 '19 at 20:44
  • 1
    From other answers, setting the length to zero crashed IE11. This answer worked for me. – Howard May 28 '21 at 15:04
30

This is a bit modern and pure JavaScript

document.querySelectorAll('#selectId option').forEach(option => option.remove())
a_rahmanshah
  • 1,636
  • 2
  • 22
  • 35
18
function removeOptions(obj) {
    while (obj.options.length) {
        obj.remove(0);
    }
}
zanetu
  • 3,740
  • 1
  • 21
  • 17
Julio Garcia
  • 665
  • 6
  • 17
8

Note that a select can have both
- optgroup &
- options collection
as its children.

So,

Method #1

var selectElement = document.getElementById('myselectid');
selectElement.innerHTML = '';

Method #2

var selectElement = document.getElementById('myselectid');
selectElement.textContent = '';

I tested, both work on Chrome.
I like the simpler, the old fashioned, method #1.

Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
8

Try

document.getElementsByTagName("Option").length=0

Or maybe look into the removeChild() function.

Or if you use jQuery framework.

$("DropList Option").each(function(){$(this).remove();});
Razor Storm
  • 12,167
  • 20
  • 88
  • 148
7

with PrototypeJS :

$('yourSelect').select('option').invoke('remove');
EpokK
  • 38,062
  • 9
  • 61
  • 69
6

If you are using JQuery and your select control has ID "DropList" you can remove its options doing this way:

$('#DropList option').remove();

Actually it works for me with any option list, like datalist.

Hope it helps.

norgematos
  • 610
  • 8
  • 18
5

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

$('#selection_box_id').empty();
Beri
  • 11,470
  • 4
  • 35
  • 57
Sobin Sunny
  • 1,121
  • 10
  • 14
  • 1
    This is really just a repeat of [this existing answer](http://stackoverflow.com/questions/3364493/how-do-i-clear-all-options-in-a-dropdown-box/3364721#3364721). – Pang Jun 15 '16 at 04:39
5

For Vanilla JavaScript there is simple and elegant way to do this:

for(var o of document.querySelectorAll('#DropList > option')) {
  o.remove()
}
Piotr
  • 1,777
  • 17
  • 24
3

Go reverse. Reason is size decreases after each remove.

for (i = (len-1); i > -1; i--) {
    document.getElementById("elementId").remove(i);
}
3

I think that is the best sol. is

 $("#myselectid").html(''); 
3

This can be used to clear options:

function clearDropDown(){
  var select = document.getElementById("DropList"),
      length = select.options.length;
  while(length--){
    select.remove(length);
  }
}
<select id="DropList" >
  <option>option_1</option>
  <option>option_2</option>
  <option>option_3</option>
  <option>option_4</option>
  <option>option_5</option>
</select>
<button onclick="clearDropDown()">clear list</button>
Pang
  • 9,564
  • 146
  • 81
  • 122
Vichu
  • 47
  • 2
3

The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null, as that may cause unexpected behaviour.

var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
    select.remove(i);

Or if you prefer, you can make it a function:

function clearOptions(id)
{
    var select = document.getElementById(id);
    for (var i = select.options.length - 1 ; i >= 0 ; i--)
        select.remove(i);
}
clearOptions("myselect");
Dan Bray
  • 7,242
  • 3
  • 52
  • 70
3
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
  select.options[i].remove();
}

Hope, this code will helps you

Nitika Chopra
  • 1,281
  • 17
  • 22
2
var select = document.getElementById('/*id attribute of your select here*/');
for (var option in select){
    select.remove(option);
}
Alex Kyllo
  • 198
  • 6
1

Above answer's code need a slight change to remove the list complete, please check this piece of code.

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length;) {
  select.options[i] = null;
  length = select.options.length;
}

refresh the length and it will remove all the data from drop down list. Hope this will help someone.

NoNaMe
  • 6,020
  • 30
  • 82
  • 110
1

The simplest solutions are the best, so You just need:

var list = document.getElementById('list');
while (list.firstChild) {
    list.removeChild(list.firstChild);
}
<select id="list">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
nitka.pawel
  • 239
  • 1
  • 5
1
for (var opt of document.querySelectorAll('#DropList option'))
{ 
  opt.remove();
}

This solution works with optgroups also.

Vasilis Plavos
  • 230
  • 2
  • 8
0
while(document.getElementById("DropList").childNodes.length>0) 
{
    document.getElementById("DropList").removeChild(document.getElementById("DropList").childNodes[0]);
}
benka
  • 4,732
  • 35
  • 47
  • 58
0

If you have to support IE and you have more than 100 items in your select list, I strongly recommend you consider replacing the select with a function like so:

function clearOptions(select) {
    var selectParentNode = select.parentNode;
    var newSelect = select.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelect, select);
    return newSelect;
}

The select parameter should be the element either from a jquery selector or document.getElementBy call. The only downside to this is that you lose events you had wired up to the select, but you can easily reattach them as it is returned back out of the function. I was working with a select that had ~3k items and it would take 4 seconds on IE9 to clear the select so I could update it with the new content. Nearly instant doing it this way.

Dan
  • 1,101
  • 1
  • 9
  • 30
  • You can find more info here: http://www.somacon.com/p542.php and more simple way: ```$('#selectbox').replaceWith($('#selectbox')[0].cloneNode(false));``` – FDisk Jul 11 '16 at 07:21
0
$("#droplist").find('select').val('default');

You can also do this to change the dropdown list goes to default. Make sure to add default in your select dropdown list like this.

"<option value="default">Select option</option>"
0

Maybe the fastest solution:

document.getElementById("DropList").replaceChildren()
0

WOW you guys really like complicating things

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

OR

  document.getElementById('idOfSelect').innerHTML = '';
0

Html

<select multiple="" class="form-select courses" name="courses">
   <option>.....</option>
   ....
</select>

JS

function ClearOptions() {
   var courseSelect = document.querySelector(".courses");

   while (courseSelect.childNodes[0] != null) {
       courseSelect.childNodes[0].remove();
   }
}

Since we are manipulating the array we are using, the index will change with each deletion. Therefore, conditions such as i > 0 do not work correctly. In this case, it would be best to continue the deletion process one by one until there are no Elements left.

Ahmet atasagun
  • 141
  • 2
  • 6
-1

Today I was facing same problem, I did as below while reloading select box. (In Plain JS)

        var select = document.getElementById("item");
        select.options.length = 0;
        var opt = document.createElement('option');
        opt.value = 0;
        opt.innerHTML = "Select Item ...";
        opt.selected = "selected";
        select.appendChild(opt);


       for (var key in lands) {
            var opt = document.createElement('option');
            opt.value = lands[key].id;
            opt.innerHTML = lands[key].surveyNo;
            select.appendChild(opt);

        }
Chowdappa
  • 1,580
  • 1
  • 15
  • 31