DOM HTMLCollection 参考手册

HTMLCollection 对象

HTMLCollection 对象是 HTML 元素的类似数组的列表。

诸如 getElementsByTagName() 之类的方法会返回 HTMLCollection。

属性和方法

可以在 HTMLCollection 对象上使用以下属性和方法:

属性 / 方法 描述
item() 返回 HTMLCollection 中指定索引处的元素。
length 返回 HTMLCollection 中的元素数。
namedItem() 返回 HTMLCollection 中有指定 ID 或名称的元素。

实例

实例

获取 HTMLCollection:

var x = document.getElementsByTagName("P");
// 返回文档中所有 P 元素的集合

亲自试一试

实例

输出文档中 <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>");
}

亲自试一试