Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select length vs. options.length

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.

like image 323
Christophe Avatar asked Sep 15 '25 07:09

Christophe


2 Answers

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

like image 130
Mike 'Pomax' Kamermans Avatar answered Sep 17 '25 21:09

Mike 'Pomax' Kamermans


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 element
  • select.options.length simply returns the number of elements in options collection (the same logic as document.getElementsByTagName('div').length)
like image 22
matewka Avatar answered Sep 17 '25 19:09

matewka