Javascript selecbox.options to array?

Rafael Herscovici picture Rafael Herscovici · May 26, 2011 · Viewed 35.9k times · Source

From what I understand a option elements that popuate select elements in HTML are an array.
So basically what i want to do is return an array string that is separated by commas.

Tried to do selecbox.options.join(',');, but got an error that its not supported; anyone have an idea why?

Answer

typeracer picture typeracer · Dec 16, 2013

The most concise solution is this:

Array.apply(null, selectbox.options)

Array.apply calls the Array constructor with the first argument as the context (i.e. this) and the second argument which is any array-like object (MDN reference).

We pass null for the first argument because we're not trying to call a method on a specific object, but rather a global constructor.

So in general,

Array.apply(null, A)

Will create a proper array containing the elements of any "array-like" object A.