最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.getElementById('').length = 0 doesn't work under Win7 - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 8
document.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 = "";
发布评论

评论列表(0)

  1. 暂无评论