js DoM NodeList 接口,HTMLCollection 接口

节点都是单个对象,有时需要一种数据结构,能够容纳多个节点。DOM 提供两种节点集合,用于容纳多个节点:NodeList和HTMLCollection。

1.NodeList实例是一个类似数组的对象,它的成员是节点对象。通过以下方法可以得到NodeList实例。
  Node.childNodes
  document.querySelectorAll()等节点搜索方法

document.body.childNodes instanceof NodeList // true

NodeList实例很像数组,可以使用length属性和forEach方法。但是,它不是数组,不能使用pop或push之类数组特有的方法

var children = document.body.childNodes;

Array.isArray(children) // false

children.length // 34
children.forEach(console.log)

如果NodeList实例要使用数组方法,可以将其转为真正的数组

var children = document.body.childNodes;
var nodeArr = Array.prototype.slice.call(children);

除了使用forEach方法遍历 NodeList 实例,还可以使用for循环

var children = document.body.childNodes;

for (var i = 0; i < children.length; i++) {
  var item = children[i];
}

注意,NodeList 实例可能是动态集合,也可能是静态集合。所谓动态集合就是一个活的集合,DOM 删除或新增一个相关节点,都会立刻反映在 NodeList 实例。目前,只有Node.childNodes返回的是一个动态集合,其他的 NodeList 都是静态集合

var children = document.body.childNodes;
children.length // 18
document.body.appendChild(document.createElement('p'));
children.length // 19

(1).NodeList.prototype.item()
 item方法接受一个整数值作为参数,表示成员的位置,返回该位置上的成员

document.body.childNodes.item(0)

(2).NodeList.prototype.keys(),NodeList.prototype.values(),NodeList.prototype.entries()
 这三个方法都返回一个 ES6 的遍历器对象,可以通过for…of循环遍历获取每一个成员的信息。区别在于,keys()返回键名的遍历器,values()返回键值的遍历器,entries()返回的遍历器同时包含键名和键值的信息。

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> ]
// ...

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

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

document.links instanceof HTMLCollection // true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值