DOM《NodeList与HTMLCollection》

86 阅读2分钟

概述

  • DOM提供两种节点集合,NodeList实例可以包含各种类型的节点,HTMLCollection只能包含HTML元素节点。

NodeList

  • NodeList是一个节点对象集合,是一个类数组。不可以使用pop、push等数组特有的方法,但可以使用length属性和forEach方法。
<div id="box1">
    123
</div>

let children = document.getElementById('box1').childNodes;
console.log(children);  // NodeList [text]

length

  • 返回包含的节点数量。

forEach()

  • 遍历所有成员,与数组forEach方法一致。
<div id="box1">
    123
</div>

let children = document.getElementById('box1').childNodes;
children.forEach(function(item, index, arr){
    console.log(item)   // " 123 "
    console.log(index)  // 0
    console.log(arr)    // NodeList [text]
})

keys()

  • 返回遍历器对象,可以通过for of遍历。此方法返回键名的遍历器。
let children = document.getElementById('box1').childNodes;
for (const key of children.keys()) {
    console.log(children[key])   // " 123 "
}

values()

  • 返回遍历器对象,可以通过for of遍历。此方法返回键值的遍历器。
let children = document.getElementById('box1').childNodes;
for (const value of children.values()) {
  console.log(value);  // " 123 "
}

entries()

  • 返回遍历器对象,可以通过for of遍历。此方法返回包含键名和键值的遍历器。
let children = document.getElementById('box1').childNodes;
for (const entry of children.entries()) {
    console.log(entry);     // [0, text]
    console.log(entry[0])   // 0
    console.log(entry[1])   // " 123 "
}

HTMLCollection

  • HTMLCollection是一个节点对象集合,只能包含元素节点,不能包含其他类型的节点。是一个类数组,但与NodeList不同的是,HTMLCollection没有forEach方法,只能使用for循环遍历。
  • HTMLCollection实例是一个活的集合,document对象的任何变化会立刻反应到实例。
<img id="image" src="https://cdn.wwads.cn/creatives/WfkH3590ZJEeUmZ7maqRpiBzvzCdiAnJOAilLgtG.jpg">
<img id="image" src="https://cdn.wwads.cn/creatives/WfkH3590ZJEeUmZ7maqRpiBzvzCdiAnJOAilLgtG.jpg">
<a href="wwww.baidu.com">百度以下</a>
<a href="wwww.baidu.com">百度以下</a>

console.log(document.images)  // HTMLCollection(2) [img#image, img#image]
console.log(document.links)   // HTMLCollection(2) [a, a]
  • 如果元素节点有idname属性,那么HTMLCollection实例上可以使用id、name引用该节点元素。如果没有对应节点则返回null
<img id="image" src="https://cdn.wwads.cn/creatives/WfkH3590ZJEeUmZ7maqRpiBzvzCdiAnJOAilLgtG.jpg">

console.dir(document.images.image)  // img#image

length

  • 返回实例包含的成员数量。

namedItem()

  • 参数为id、name属性的值,返回当前集合中对应的元素节点。
<img id="image" src="https://cdn.wwads.cn/creatives/WfkH3590ZJEeUmZ7maqRpiBzvzCdiAnJOAilLgtG.jpg">

console.log(document.images.namedItem('image') === document.images.image)  // true 与直接写id/name功能一致