Friday, May 17, 2024
187
rated 0 times [  190] [ 3]  / answers: 1 / hits: 29394  / 11 Years ago, mon, april 22, 2013, 12:00:00

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?


More From » createelement

 Answers
30

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


[#78730] Saturday, April 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;