Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create option elements in Javascript

Tags:

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?

like image 545
GOTO 0 Avatar asked Apr 22 '13 10:04

GOTO 0


People also ask

How do you add dynamic options?

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.

Which of the given option is used to add new element dynamically?

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.

How do you set a select option value dynamically in typescript?

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.


2 Answers

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

like image 82
MaxArt Avatar answered Sep 19 '22 03:09

MaxArt


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.

like image 32
goe Avatar answered Sep 21 '22 03:09

goe