• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • HTMLCollection 接口

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

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

    document.links instanceof HTMLCollection // true
    

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

    如果元素节点有idname属性,那么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']