Select add() Method
Definition and Usage
add()
This method is used to add options to the dropdown list.
Tip:To remove an option from the dropdown list, use remove() Method.
Example
Example 1
Add the "Kiwi" option at the end of the dropdown list:
var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = "Kiwi"; x.add(option);
Example 2
Add the "Kiwi" option at the beginning of the dropdown list:
var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = "Kiwi"; x.add(option, x[0]);
Example 3
Add the "Kiwi" option at the index position "2" in the dropdown list:
var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = "Kiwi"; x.add(option, x[2]);
Example 4
Add an option before the selected option in the dropdown list:
var x = document.getElementById("mySelect"); if (x.selectedIndex >= 0) { var option = document.createElement("option"); option.text = "Kiwi"; var sel = x.options[x.selectedIndex]; x.add(option, sel); }
Syntax
selectObjectadd(option, index)
Parameter Value
Parameter | Description |
---|---|
option | Required. Specifies the option to be added. It must be an option or optgroup element. |
index |
Optional. Integer, specifies the index position where the new option element should be inserted. The index starts from 0. If the index is not specified, the new option will be inserted at the end of the list. |
Technical Details
Return Value:
No Return Value.
Browser Support
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support |