HTMLCollection 接口

HTMLCollection 是一个节点对象的集合,只能包含元素节点(element),不能包含其他类型的节点。它的返回值是一个类似数组的对象,但是与 NodeList 接口不同, HTMLCollection 没有 forEach 方法,只能使用 for 循环遍历。

返回 HTMLCollection 实例的,主要是一些 Document 对象的集合属性,比如 document.links document.forms document.images 等。

document.links instanceof HTMLCollection // true

HTMLCollection 实例都是动态集合,节点的变化会实时反映在集合中。

如果元素节点有 id name 属性,那么 HTMLCollection 实例上面,可以使用 id 属性或 name 属性引用该节点元素。如果没有对应的节点,则返回 null

// HTML 代码如下
// <img id="pic" src="http://example.com/foo.jpg">

var pic = document.getElementById('pic');
document.images.pic === pic // true

上面代码中, document.images 是一个 HTMLCollection 实例,可以通过 <img> 元素的 id 属性值,从 HTMLCollection 实例上取到这个元素。


HTMLCollection.prototype.length

length 属性返回 HTMLCollection 实例包含的成员数量。

document.links.length // 18


HTMLCollection.prototype.item()

item 方法接受一个整数值作为参数,表示成员的位置,返回该位置上的成员。

var c = document.images;
var img0 = c.item(0);

上面代码中, item(0) 表示返回0号位置的成员。由于方括号运算符也具有同样作用,而且使用更方便,所以一般情况下,总是使用方括号运算符。

如果参数值超出成员数量或者不合法(比如小于0),那么 item 方法返回 null


HTMLCollection.prototype.namedItem()

namedItem 方法的参数是一个字符串,表示 id 属性或 name 属性的值,返回当前集合中对应的元素节点。如果没有对应的节点,则返回 null

// HTML 代码如下
// <img id="pic" src="http://example.com/foo.jpg">

var pic = document.getElementById('pic');
document.images.namedItem('pic') === pic // true

Collection.namedItem('value') 等同于 Collection['value']