1

I've a HTML code snippet like follows:

<form>
  <select name="mySelect">
    <option value="1">text_1</option>
    <option value="2">text_2</option>
  </select>
</form>

I found out that in Internet Explorer, Javascript below can work:

document.forms[0].mySelect.options(0).text

But in Firefox or Chrome, it can not work and reports such error message:

document.forms[0].mySelect.options is not a function

In my opinion, mySelect.options should be an array, thus must be accessed by mySelect.options[0]. I also checked the DOM api and found no options function available.

Does it mean in the IE javascript engine, all arrays can be treated as both a collection and a function? Any advice will be appreciated, thanks in advance!

5
  • 1
    document.forms[0].mySelect.options[0] Commented Apr 10, 2014 at 6:12
  • Because IE confuses property access with method calls, use square brackets: ...options[0].text Commented Apr 10, 2014 at 6:13
  • It should be noted that referring to a form via document.forms[0] is a bad idea in principle as it will break the moment you decide to add another form to that page (like a login form, or a sidebar form). Much better off to use document.getElementById( 'FORMID' ).mySelect... Commented Apr 10, 2014 at 6:18
  • @TomMcQuarrie, thanks! Actually I know forms[0] is a bad idea and for me I only use JQuery to ignore such browser differences. This is a snippet from a legacy project which causes me a bit confused. Commented Apr 10, 2014 at 6:25
  • Related post - JavaScript array index 'undefined' in Internet Explorer Commented Jun 25, 2019 at 5:57

1 Answer 1

2

Notice, that options is not an array, it's HTMLCollection, which is an array-like object. This is also a host object, hence it can behave differently from JS objects.

In IE you can call HTMLCollection as it was a function (at least in older IEs):

select.options(vIndex [, iSubIndex] );

Here vIndex is either an integer representing an index, or a string referring name property. As you can have multiple similar names, iSubIndex is used to construct a collection of all elements that have a name or id property equal to the string, and then retrieves from this collection the element at the position specified by iSubIndex.

Sign up to request clarification or add additional context in comments.

1 Comment

noted and thanks, actually I also tested on IE11 and it can work. Guess IE also sticks to its tradition, :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.