I have a select list:
<select id="sel">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
</select>
I want to delete all items, without for
loop.
I tried:
document.getElementById('sel').length = 0;
But this doesn't work in some browsers.
Any ideas?
Thanks
I have a select list:
<select id="sel">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
</select>
I want to delete all items, without for
loop.
I tried:
document.getElementById('sel').length = 0;
But this doesn't work in some browsers.
Any ideas?
Thanks
Share Improve this question edited May 18, 2010 at 16:57 Simon asked May 18, 2010 at 16:14 SimonSimon 23.2k36 gold badges93 silver badges122 bronze badges2 Answers
Reset to default 8document.getElementById( 'sel' ).innerHTML = '';
Moved from ment:
You should understand such a length
property more like a read-only property that gives you information about the state of the object. Like when you get the length of an array. Changing that value however doesn't affect the actual object, while removing an element correctly will cause the browser to re-render the DOM for that element (and as such update the value). I guess some browsers might interpret setting a length to zero will clear that object but in general that shouldn't be the expected behaviour. Also I think Element.length
actually isn't part of the DOM specification.
To add some references to that, the core DOM Element doesn't have any length parameter. Both the HTMLSelectElement and the HTMLOptionsCollection (which can be accessed via HTMLSelectElement.options
) have a length attribute but setting it should raise a DOMException.
So in both ways setting the length is illegal by the standard and as such should not be used if you want to support most browsers.
Either of these work:
document.getElementById('sel').options.length = 0;
or
document.getElementById('sel').innerHTML = "";