Wählen Sie die Methode add() aus
Beispiel
Fügen Sie eine "Kiwi"-Option am Ende einer Dropdown-Liste hinzu:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
Definition und Verwendung
Die Methode add() wird verwendet, um eine Option zu einer Dropdown-Liste hinzuzufügen.
Tipp: Um eine Option aus einer Dropdown-Liste zu entfernen, verwenden Sie die Methode remove() .
Browser-Unterstützung
Method | |||||
---|---|---|---|---|---|
add() | Yes | Yes | Yes | Yes | Yes |
Syntax
selectObject.add(option, index)
Parameterwerte
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 |
Technische Details
Rückgabewert: | Kein Rückgabewert |
---|
Mehr Beispiele
Beispiel
Fügen Sie eine "Kiwi"-Option am Anfang einer Dropdown-Liste hinzu:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[0]);
Beispiel
Fügen Sie eine "Kiwi"-Option an Indexposition "2" einer Dropdown-Liste hinzu:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[2]);
Beispiel
Fügen Sie eine Option vor einer ausgewählten Option in einer Dropdown-Liste hinzu:
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);
}
❮ Objekt auswählen