แบบฟอร์มเอกสาร HTML DOM
ตัวอย่าง
จำนวน <form> องค์ประกอบในเอกสาร:
let num = document.forms.length;
รับ id ขององค์ประกอบ <form> แรก:
let id = document.forms[0].id;
รับ id ขององค์ประกอบ <form> แรก:
let id = document.forms.item(0).id;
รับเนื้อหา HTML ขององค์ประกอบ <form> ด้วย id="myCarForm":
let html = document.forms.namedItem("myCarForm").innerHTML;
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
คุณสมบัติforms
ส่งคืนคอลเลกชันขององค์ประกอบ <form> ทั้งหมดในเอกสาร
คุณสมบัติส่งforms
คืนHTMLCollection
คุณสมบัติforms
เป็นแบบอ่านอย่างเดียว
ดูสิ่งนี้ด้วย:
บทช่วยสอนเกี่ยวกับแบบฟอร์ม HTML
เคล็ดลับ:
ใช้คอลเลกชันองค์ประกอบแบบฟอร์มเพื่อส่งคืนองค์ประกอบทั้งหมดในแบบฟอร์ม
HTMLCollection
HTMLCollection คือ ชุดของโหนด HTML
โหนดในคอลเล็กชันสามารถเข้าถึงได้ด้วยหมายเลขดัชนี ดัชนีเริ่มต้นที่ 0
คุณสมบัติความยาวส่งคืนจำนวนองค์ประกอบในคอลเลกชัน
ไวยากรณ์
document.forms
คุณสมบัติ
Property | Description |
length | The number of elements in the collection. |
วิธีการ
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. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
วัตถุ | วัตถุHTMLCollection องค์ประกอบ <form> ทั้งหมดในเอกสาร เรียงตามที่ปรากฏในซอร์สโค้ด |
ตัวอย่างเพิ่มเติม
วนรอบองค์ประกอบ <form> ทั้งหมดและส่งออก id ของแต่ละแบบฟอร์ม:
const forms = document.forms;
let text = "";
for (let i = 0; i < forms.length; i++) {
text += forms[i].id + "<br>";
}
การใช้คอลเลกชัน form.elementsเพื่อรับ ค่าของแต่ละองค์ประกอบในแบบฟอร์ม:
const form = document.forms[0];
let text = "";
for (let i = 0; i < form.length; i++) {
text += forms.elements[i].value + "<br>";
}
รองรับเบราว์เซอร์
document.forms
เป็นคุณลักษณะ DOM ระดับ 1 (1998)
ได้รับการสนับสนุนอย่างเต็มที่ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |