add()メソッドを選択します
例
ドロップダウンリストの最後に「Kiwi」オプションを追加します。
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
定義と使用法
add()メソッドは、ドロップダウンリストにオプションを追加するために使用されます。
ヒント:ドロップダウンリストからオプションを削除するには、 remove()メソッドを使用します。
ブラウザのサポート
Method | |||||
---|---|---|---|---|---|
add() | Yes | Yes | Yes | Yes | Yes |
構文
selectObject.add(option, index)
パラメータ値
Parameter | Description |
---|---|
option | Required. Specifies the option to add. Must be an option or optgroup element |
index | Optional. An integer that specifies the index position for where the new option element should be inserted. Index starts at 0. If no index is specified, the new option will be inserted at the end of the list |
技術的な詳細
戻り値: | 戻り値なし |
---|
その他の例
例
ドロップダウンリストの先頭に「Kiwi」オプションを追加します。
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[0]);
例
ドロップダウンリストのインデックス位置「2」に「Kiwi」オプションを追加します。
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[2]);
例
ドロップダウンリストで選択したオプションの前にオプションを追加します。
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);
}
❮オブジェクトを選択