NodeList
对象是一个节点的集合,是由Node.childNodes
and the querySelectorAll返回的.node
length
数组
NodeList对象
中包含的节点个数.浏览器
item ( idx )
app
返回NodeList对象中指定索引的节点,若是索引越界,则返回null
.也能够简写为nodeList[idx].
spa
大多数状况下,NodeList
对象都是个live集合.意思是说,若是文档中的节点树发生变化,则已经存在的NodeList对象也可能会变化.prototype
var links = document.getElementsByTagName('a');// 假如如今links.length === 2.document.body.appendChild( links[0].cloneNode(true) ); // 文档中又添加了一个a.// 则links这个NodeList对象也会改变.// links.length === 3
但若是该NodeList
对象是由document.querySelectorAll
(或者Element.querySelectorAll
)方法返回的, 则它是非live的(就算把页面内的全部节点清空,links.length
还等于2).code
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
对象用不了它们.
一个解决办法就是把Array.prototype
上的方法添加到NodeList.prototype
上. 但是, 要注意扩展DOM对象的原型是很是危险的,尤为是在旧版本的Internet Explorer(6,7,8)中
for(prop in Array.prototype){ if(Array.prototype.hasOwnProperty(prop) && typeof(Array.prototype[prop]) === 'function') NodeList[prop] = Array.prototype[prop];}var links = document.getElementsByTagName('a');links.forEach(function(link){ // 在一些浏览器中会抛异常 link.style.color = '#0F0';});
不扩展DOM对象原型的解决办法:
var forEach = Array.prototype.forEach;var links = document.getElementsByTagName('a');forEach.call(links, function(link){ // 未发现有浏览器不支持 link.style.color = '#0F0';});
遍历一个NodeList
对象中的全部的节点可使用以下代码:
for (var i = 0; i < myNodeList.length; ++i) { var item = myNodeList[i]; // 能够简写为myNodeList[i].}
不要尝试使用 for...in
或者 for each...in
来遍历一个NodeList
对象中的元素, 由于NodeList
对象中的length和item属性也会被遍历出来,这可能会致使你的脚本运行出错,若是你把上述两个属性也当作DOM对象的话.