【转】 HTMLCollection和NodeList的区别

1 HTMLCollection类型

下面的每个项目(以及它们指定的属性)都返回 HTMLCollection(基类)或者它的派生类:
Document (images, applets, links, forms, anchors)
form (elements)
map (areas)
select (options)
table (rows, tBodies)
tableSection (rows)
row (cells)

document.forms 是一个 HTMLCollection类型的值
document还有images, applets, links, forms, anchors也返回HTMLCollection类型

var links = document.getElementsByTagName('a');//links返回HTMLCollection集合

属性Properties
length 只读 表示集合的数量 The number of items in the collection.

方法Methods
HTMLCollection.item(index)
根据数字索引值返回对象
HTMLCollection.namedItem(name)
根据name或者id索引值返回对象

举个例子:
在Dom中有个表单form元素,它的id是'myForm'
var elem1, elem2;

// document.forms is an HTMLCollection

elem1 = document.forms[0];
elem2 = document.forms.item(0);

alert(elem1 === elem2); // shows: "true"

elem1 = document.forms["myForm"];
elem2 = document.forms.namedItem("myForm");

alert(elem1 === elem2); // shows: "true"

注意
HTMLCollection 是“活”的;如果基本的文档改变时,那些改变通过所有 HTMLCollection 对象会立即显示出来。

2 NodeList类型

概述
NodeList对象是一个节点的集合,是由Node.childNodes and the querySelectorAll方法返回的.

属性
length
NodeList对象中包含的节点个数.

方法
item ( idx )
返回NodeList对象中指定索引的节点,如果索引越界,则返回null.也可以简写为nodeList[idx].

描述
一个"live"集合

综合:
document.getElementsByName返回NodeList集合
var elems = document.getElementsByName('f');
console.dir(elems)//NodeList[3]

document.getElementsByTagName 返回HTMLCollection集合
var links = document.getElementsByTagName('a')
console.dir(links)//HTMLCollection[102]

大多数情况下,NodeList对象和HTMLCollection都是个live集合.意思是说,如果文档中的节点树发生变化,则已经存在的NodeList对象也可能会变化.

var links = document.getElementsByTagName('a');
// 假如现在links.length === 2.

document.body.appendChild( links[0].cloneNode(true) ); // 文档中又添加了一个a.
// 则links这个NodeList对象也会改变.
// links.length === 3

但如果该集合是由document.querySelectorAll(或者Element.querySelectorAll)方法返回的, 则它是非live的(就算把页面内的所有节点清空,links.length还等于2).

判断集合是哪一种的方法:
1 通过集合是否有namedItem这个方法判断是属于HTMLCollection集合 还是NodeList集合
2 通过打压其构造函数也可以知道 links.constructor
3 通过Object.getPrototypeOf(links对象)

什么NodeList对象没有map和forEach方法?

NodeList对象在某些方面和数组非常相似,看上去可以直接使用从Array.prototype上继承的方法.然而,这是不可以的.

JavaScript的继承机制是基于原型的.数组元素之所以有一些数组方法( 比如forEach和map),是因为它的原型链上有这些方法,如下:

myArray --> Array.prototype --> Object.prototype --> null (想要获取一个对象的原型链,可以连续的调用Object.getPrototypeOf,直到原型链尽头).

forEach, map这些方式其实是 Array.prototype这个对象的方法.

和数组不一样, NodeList的原型链是这样的:

myNodeList --> NodeList.prototype --> Object.prototype --> null

NodeList.prototype只有一个item方法, 没有Array.prototype上的那些方法, 所以NodeList对象用不了它们.

原文链接:http://kezhou.sinaapp.com/index.php/archives/40.html

原文地址:https://www.cnblogs.com/coder-dumeng/p/5217404.html