Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Bộ sưu tập forms trong HTML DOM

Bộ sưu tập document.forms trả về tất cả các phần tử <form> trong tài liệu dưới dạng HTMLCollection, theo thứ tự xuất hiện trong HTML.

Thuộc tính

Thuộc tínhMô tả
lengthSố lượng form trong bộ sưu tập (read-only).

Phương thức

Phương thứcMô tả
[index]Trả về form tại chỉ số index (bắt đầu từ 0), null nếu vượt giới hạn.
item(index)Giống [index].
namedItem(id)Trả về form có id cho trước, null nếu không tồn tại.

Cú pháp

document.forms

Ví dụ

Liệt kê ID của tất cả form:

<!DOCTYPE html> <html> <head> 
<script> 
  function formCollect() { 
    for (var i = 0; i < document.forms.length; i++) { 
      var no = document.forms[i].id + "<br>"; 
      document.getElementById("Sample").innerHTML += no; 
    } 
  } 
</script> </head> 
<body> 
<h1>Ví dụ forms collection</h1> 
<form id="FORM1"> Fruit <input type="text" name="fname" value="Mango"> </form> 
<form id="FORM2"> Age <input type="text" name="Age" value="22"> </form> 
<form id="FORM3"> Password: <input type="password" name="pass" value="test"> </form> 
<br> 
<button onclick="formCollect()">LẤY ID FORM</button> 
<p id="Sample">Các form ID:<br></p> 
</body> </html>

Kết quả

Ban đầu:

Bộ sưu tập forms trong HTML DOM

Sau khi nhấn nút, hiển thị 3 ID form:

Bộ sưu tập forms trong HTML DOM