DOM HTMLCollection
Đối tượng HTMLCollection
Đối tượng HTMLCollection là một danh sách các phần tử HTML giống như một mảng.
Các phương thức như getElementsByTagName () trả về một HTMLCollection.
Thuộc tính và phương pháp
Các thuộc tính và phương thức sau có thể được sử dụng trên đối tượng 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 |
Các ví dụ
Thí dụ
Nhận bộ sưu tập HTMLC:
var x = document.getElementsByTagName("P");
// Returns a
collection of all the P elements in the document
Thí dụ
Viết số phần tử <p> trong tài liệu:
var x = document.getElementsByTagName("P");
document.write(x.length);
Thí dụ
Lặp lại mọi phần tử trong bộ sưu tập HTMLC:
x = document.getElementsByTagName("*");
l = x.length;
for (i = 0; i <
l; i++) {
document.write(x[i].tagName + "<br>");
}