NodeList 接口 HTMLCollection 接口node
节点都是单个对象,有时须要一种数据结构,可以容纳多个节点数组
DOM 提供两种节点集合,用于容纳多个节点:NodeList 和 HTMLCollection数据结构
这两种集合都属于接口规范。app
许多 DOM 属性和方法,返回的结果是 NodeList 实例或 HTMLCollection 实例。函数
主要区别是this
NodeList 能够包含各类类型的节点spa
HTMLCollection 只能包含 HTML 元素节点。prototype
NodeList 接口code
var children = document.body.childNodes; Array.isArray(children); // false children.length; // 34 children.forEach(console.log); // forEach() 遍历 NodeList 实例
for (var i = 0; i < children.length; i++) { // for 遍历 NodeList 实例 var item = children[i]; }
若是 NodeList 实例要使用数组方法,能够将其转为真正的数组orm
var children = document.body.childNodes; var nodeArr = Array.prototype.slice.call(children);
var children = document.body.childNodes; children.length; // 18 document.body.appendChild(document.createElement('p')); children.length; // 19 // 文档增长一个子节点,NodeList 实例 的 属性就增长了1childrenlength
document.getElementsByTagName('xxx').length; // 0
var children = document.body.childNodes; children.forEach(function f(item, i, list) { // ... }, this); // forEach方法的第二个参数,用于绑定回调函数内部的this,该参数可省略 // 回调函数f的三个参数依次是 // 当前成员 // 在类数组中的 index // 当前 NodeList 实例。
item
方法。document.body.childNodes.item(0); // item(0)返回第一个成员
document.body.childNodes[0]; // 最为经常使用
var children = document.body.childNodes; for (var key of children.keys()) { console.log(key); } // 0 // 1 // 2 // ... for (var value of children.values()) { console.log(value); } // #text // <script> // ... for (var entry of children.entries()) { console.log(entry); } // Array [ 0, #text ] // Array [ 1, <script> ] // ...
HTMLCollection 接口
document.links instanceof HTMLCollection // true
// HTML 代码以下 // <img id="pic" src="http://example.com/foo.jpg"> var pic = document.getElementById('pic'); document.images.pic === pic // true
document.links.length // 18
var c = document.images; var img0 = c.item(0); var img0 = c[0]; // 更经常使用 [ ]
// HTML 代码以下 // <img id="pic" src="http://example.com/foo.jpg"> var pic = document.getElementById('pic'); document.images.namedItem('pic') === pic // true