25

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?

2 Answers 2

13

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...

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

3 Comments

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, @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 In 2013 that wasn't the case but good to know it is no longer so.
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.

1 Comment

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.

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.