DOM HTMLCollection
วัตถุ HTMLCollection
วัตถุ HTMLCollection เป็นรายการองค์ประกอบ HTML ที่เหมือนอาร์เรย์
เมธอดเช่น getElementsByTagName() ส่งคืน HTMLCollection
คุณสมบัติและวิธีการ
สามารถใช้คุณสมบัติและเมธอดต่อไปนี้บนอ็อบเจ็กต์ HTMLCollection:
Property / Method | Description |
---|---|
item() | Returns the element at the specified index in an HTMLCollection |
length | Returns the number of elements in an HTMLCollection |
namedItem() | Returns the element with the specified ID, or name, in an HTMLCollection |
ตัวอย่าง
ตัวอย่าง
รับ HTMLCollection:
var x = document.getElementsByTagName("P");
// Returns a
collection of all the P elements in the document
ตัวอย่าง
เขียนจำนวน <p> องค์ประกอบในเอกสาร:
var x = document.getElementsByTagName("P");
document.write(x.length);
ตัวอย่าง
วนซ้ำทุกองค์ประกอบใน HTMLCollection:
x = document.getElementsByTagName("*");
l = x.length;
for (i = 0; i <
l; i++) {
document.write(x[i].tagName + "<br>");
}