23

What is the preferred way in Javascript to dynamically create DOM option elements? I've found both the Option constructor and the createElement variant used in actual code like this:

var option = new Option(text, value);

and this:

var option = document.createElement('option');
option.text = text;
option.value = value;

Are there any drawbacks/compatibility issues with any of those methods? Also, are there any other methods to create options dynamically that should be preferred to the above for some reasons?

GOTO 0
  • 42,323
  • 22
  • 125
  • 158

2 Answers2

12

There are no differences between the two methods that I know of. Using the Option constructor allows you to conveniently set the value and the text of the option, but you can do the same using the value and text properties.

There could have been the innerHTML way, but IE8 and older fail hard on this...

MaxArt
  • 22,200
  • 10
  • 82
  • 81
  • 1
    Though it will have no effect on the code, there is a minor difference. Using `var option = new Option();` will result in `option` being an instance of the `Option` Object and `option instanceof Option` is `true`, while using `var option = document.createElement('option');` will result in `option` being a literal and not an instance of the `Option` Object, hence `option instanceof Option` is `false`; Though both will have been created from the same `constructor` and `option.constructor` will be `function HTMLOptionElement()`. – Nope Dec 18 '13 at 23:23
  • 1
    Nope, @Nope, that's not so. `document.createElement("option") instanceof Option` returns true, contrary to what you said. You would expect this, as however the object get created, it is an instance of the same kind of DOM object. – Doin Mar 14 '20 at 11:53
  • @Doin In 2013 that wasn't the case but good to know it is no longer so. – Nope Mar 24 '20 at 10:00
1

I noticed for example that using new Option() doesn't work well under IE9 where it works in IE10 and IE11. I recently had go back to the original code and revert the change somebody did to go back using document.createElement('option') in order for IE9 to work.

goe
  • 1,153
  • 2
  • 12
  • 24
  • This is not entirely accurate. Where I work there is a large set of legacy code developed for IE6 that uses new Option(). Perhaps there is another issue in your code that's prevented it from working. – Danny C Apr 28 '15 at 08:53