Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top