Select Length Vs. Options.length
Solution 1:
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 asselect.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 howselect.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
Solution 2:
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 wordslength
in select is a special property of this particular DOM elementselect.options.length
simply returns the number of elements inoptions
collection (the same logic asdocument.getElementsByTagName('div').length
)
Solution 3:
It's not the same definitely I had to find out the hardway trying
There are 3 options defined in the HTML/PHP
Calling a JQUERY function and results are
Before selecting anything in the combobox
console.log(select.length); // 1
console.log(select.options.length); // undefined
After selecting something
console.log(select.length); // 3
console.log(select.options.length); // 3
Post a Comment for "Select Length Vs. Options.length"