For a select element, is there any difference between the length
property and the options.length
property?
In particular, I'd be interested to know if there's a difference in terms of browser support.
Based on https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement there is no functional difference, only a "semantic if you want to get really technical about it" difference:
select.length
is formally declared as the number of option elements contained by a select element. It will by spec-definition always have the same value as select.options.length
, which is:
select.options.length
is "the number of elements in the list of options childNodes on the select element". Technical difference, semantically slightly different, but due to how select.length
has been formalised, for all intents and purposes always the same value.
So the first technically "lives" on the <select>
element, the second lives on the options
property of the <select>
element (which is an HTMLOptionsCollection, not an array!), but the value's always the same and it doesn't really matter which you use. Browsers that implement the spec (see [1] and [2]) always give the correct value for either.
[1] http://www.w3.org/TR/2002/PR-DOM-Level-2-HTML-20021108/html.html#ID-5933486
[2] http://www.w3.org/TR/2002/PR-DOM-Level-2-HTML-20021108/html.html#HTMLOptionsCollectionwill
Both
select.length
and
select.options.length
are supported by all major browsers.
The only difference between them (as far as I know) is
select.length
is select property which returns its number of options - that's the definition. In other words length
in select is a special property of this particular DOM elementselect.options.length
simply returns the number of elements in options
collection (the same logic as document.getElementsByTagName('div').length
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With