Formulare für HTML-DOM-Dokumente
Beispiel
Anzahl der <form>-Elemente im Dokument:
let num = document.forms.length;
Rufen Sie die ID des ersten <form>-Elements ab:
let id = document.forms[0].id;
Rufen Sie die ID des ersten <form>-Elements ab:
let id = document.forms.item(0).id;
Holen Sie sich den HTML-Inhalt des <form>-Elements mit id="myCarForm":
let html = document.forms.namedItem("myCarForm").innerHTML;
Weitere Beispiele unten.
Definition und Verwendung
Die forms
Eigenschaft gibt eine Auflistung aller <form>-Elemente in einem Dokument zurück.
Die forms
Eigenschaft gibt eine HTMLCollection zurück .
Die forms
Eigenschaft ist schreibgeschützt.
Siehe auch:
Das Tutorial zu HTML-Formularen
Spitze:
Verwenden Sie die Forms-Elemente-Auflistung , um alle Elemente in einem Formular zurückzugeben.
HTMLCollection
Eine HTMLCollection ist eine Sammlung von HTML-Knoten.
Auf Knoten in einer Sammlung kann über Indexnummern zugegriffen werden. Der Index beginnt bei 0.
Die Eigenschaft length gibt die Anzahl der Elemente in der Sammlung zurück.
Syntax
document.forms
Eigenschaften
Property | Description |
length | The number of elements in the collection. |
Methoden
Method | Description |
[index] | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
item(index) | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
namedItem(id) | Returns the element with the specified id. Returns null if the id does not exist. |
Rückgabewert
Typ | Beschreibung |
Objekt | Ein HTMLCollection-Objekt . Alle <form>-Elemente im Dokument. Sortiert, wie sie im Quellcode erscheinen |
Mehr Beispiele
Durchlaufen Sie alle <form>-Elemente und geben Sie die ID jedes Formulars aus:
const forms = document.forms;
let text = "";
for (let i = 0; i < forms.length; i++) {
text += forms[i].id + "<br>";
}
Verwenden der form.elements-Sammlung , um den Wert jedes Elements im Formular abzurufen:
const form = document.forms[0];
let text = "";
for (let i = 0; i < form.length; i++) {
text += forms.elements[i].value + "<br>";
}
Browser-Unterstützung
document.forms
ist eine Funktion von DOM Level 1 (1998).
Es wird in allen Browsern vollständig unterstützt:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |