NodeList

NodeList


概述

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

属性

length数组

  • NodeList对象中包含的节点个数.浏览器

方法

  • item ( idx )app

  • 返回NodeList对象中指定索引的节点,若是索引越界,则返回null.也能够简写为nodeList[idx].spa

描述

一个"live"集合

大多数状况下,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对象没有map和forEach方法?

NodeList对象在某些方面和数组很是类似,看上去能够直接使用从Array.prototype上继承的方法.然而,这是不能够的.对象

JavaScript的继承机制是基于原型的.数组元素之因此有一些数组方法( 好比forEachmap),是由于它的原型链上有这些方法,以下:继承

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

forEachmap这些方式实际上是 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对象的话.

相关文章
相关标签/搜索