DOM提供两种节点集合,用于容纳多个节点:NodeList和HTMLCollection;NodeList可以包含各种类型的节点;HTMLCollection只能包含HTML元素节点
1. NodeList
1.1 概述
NodeList是类数组对象,成员是节点对象- 通过
childNodes和document.querySelectorAll()来得到NodeList实例 只有
childNodes返回一个动态集合,其他的NodeList都是静态集合1.2 NodeList.prototype.length
-
1.3 NodeList.prototype.forEach()
-
1.4 NodeList.prototype.item()
接收一个整数值为参数,表示成员的位置,返回该位置上的成员
document.body.childNodes.item(0)
一般使用下标来获取
document.body.childNodes[0]
1.5 NodeList.prototype.keys() NodeList.prototype.values() NodeList.prototype.entries()
2 HTMLCollection接口
2.1 概述
HTMLCollection是一个节点对象的集合,只能包含元素节点(element)- 是一个类数组对象,但是和
NodeList不同的是HTMLCollection没有forEach方法,只能使用for循环 - 返回
HTMLCollection实例的,主要是一些Document对象的集合属性,如:- document.links
- document.forms
- document.images
HTMLCollection实例是动态集合,节点的变化会实时反映在集合元素节点上有
id或name属性时,那么HTMLCollection实例上面,可以使用id属性或name属性引用该节点<img id="pic" src="http://example.com/a.jpg">var pic = document.images.pic;
2.2 HTMLCollection.prototype.length
2.3 HTMLCollection.prototype.item()
2.4 HTMLCollection.prototype.namedItem()
参数是字符串,表示id属性或name属性的值,返回对应的元素节点
