概述
- DOM提供两种节点集合,
NodeList实例可以包含各种类型的节点,HTMLCollection只能包含HTML元素节点。
NodeList
- NodeList是一个节点对象集合,是一个类数组。不可以使用
pop、push等数组特有的方法,但可以使用length属性和forEach方法。
<div id="box1">
123
</div>
let children = document.getElementById('box1').childNodes;
console.log(children);
length
forEach()
<div id="box1">
123
</div>
let children = document.getElementById('box1').childNodes;
children.forEach(function(item, index, arr){
console.log(item)
console.log(index)
console.log(arr)
})
keys()
- 返回遍历器对象,可以通过
for of遍历。此方法返回键名的遍历器。
let children = document.getElementById('box1').childNodes;
for (const key of children.keys()) {
console.log(children[key])
}
values()
- 返回遍历器对象,可以通过
for of遍历。此方法返回键值的遍历器。
let children = document.getElementById('box1').childNodes;
for (const value of children.values()) {
console.log(value);
}
entries()
- 返回遍历器对象,可以通过
for of遍历。此方法返回包含键名和键值的遍历器。
let children = document.getElementById('box1').childNodes;
for (const entry of children.entries()) {
console.log(entry);
console.log(entry[0])
console.log(entry[1])
}
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]
- 如果元素节点有
id或name属性,那么HTMLCollection实例上可以使用id、name引用该节点元素。如果没有对应节点则返回null。
<img id="image" src="https://cdn.wwads.cn/creatives/WfkH3590ZJEeUmZ7maqRpiBzvzCdiAnJOAilLgtG.jpg">
console.dir(document.images.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)