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?
The HTMLSelectElement type represents the <select> element. It has the add() method that dynamically adds an option to the <select> element and the remove() method that removes an option from the <select> element: add(option,existingOption) – adds a new <option> element to the <select> before an existing option.
New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.
In reactive form we can use setValue and patchValue of FormGroup and in template-driven form we can use ngModel to set value in select box dynamically. We can also use 'selected' attribute in <option> tag of select element to set default value selected in select box.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With