【转】 HTMLCollection和NodeList的区别

1 HTMLCollection类型

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

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

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

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

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

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

// document.forms is an HTMLCollectionspa

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

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

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

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

相关文章
相关标签/搜索