Understanding a NodeList object and its relatives, NamedNodeMap and HTMLCollection, is critical to a good understanding of the DOM as a while. Each of those collections is considered "live", which is to say that they are updated when the document structure changes such that they are always current with the most accurate information. In reality, all NodeList objects are queries that are run against the DOM document whenever they are accessed. For instance, the following results in an infinite loop:

 var divs = document.getElementsByTagName("div"),
i,
div; for (i=0; i<div.length; i++){
div = document.createElement("div");
document.body.appendChild(div);
}

  The first part of this code gets an HTMLCollection of all <div> elements in the document. Since that collection is "live", any time a new <div> element is added to the page, it gets added into the collection. Since the browser doesn't want to keep a list of all the collections that were created, the collection is updated only when it is accessed again. This creates an interesting problem in terms of a loop such as the one in this example. Each tiem through the loop, the condition i<divs.length is being evaluated. That means the query to get all <div> elements is being run. Because the body of the loop creates a new <div> element and adds it to the document, the value of divs.length increments each time through the loop;

  Any time you want to iterate over a NodeList, it's best to initialize a second variable with the length and then compare the iterator to that variable, as shown in the following example:

 var divs = document.getElementsByTagName("div"),
i,
len,
div; for (i=0, len=divs.length; i<len; i++){
div = document.createElement("div");
document.body.appendChild(div);
}

  Generally speaking, it is best to limit the number of times you interact with a NodeList. Since a query is run against the document each time, try to cache frequently used values retrieved from a NodeList.

最新文章

  1. php实现的笛卡儿积
  2. Logcat打印调试信息
  3. http://www.cnblogs.com/vowei/archive/2012/08/24/2654287.html
  4. Table of Contents - HttpClient
  5. MATLAB曲线绘制
  6. BZOJ2542: [Ctsc2001]终极情报网
  7. PieTTY
  8. libcurl下载文件简易demo
  9. hdu 1022 Train Problem I(栈)
  10. jni开发中的常见错误
  11. C++风格写判断某年某月某日是一年的第几天
  12. MIP开发教程(一) MIP-CLI工具安装与环境部署
  13. 20175204 张湲祯 2018-2019-2《Java程序设计》第七周学习总结
  14. java快排思想
  15. centos7安装配置jdk
  16. iTerm2使用技巧
  17. Android Studio 之 注释模板
  18. D5 F
  19. Python-python中数组和列表读取一列的方法
  20. spring mvc返回json格式和json字符串

热门文章

  1. 异步消息处理机制相关面试问题-intentservice面试问题详解
  2. MySQL in和limit不能连用的问题
  3. Loadrunner:录制APP脚本
  4. 从零开始实现一个简易的Java MVC框架(三)--实现IOC
  5. 银行卡号Luhn校验算法
  6. 关于怎么获取kafka指定位置offset消息(转)
  7. Neko does Maths CodeForces - 1152C 数论欧几里得
  8. Vue_(组件通讯)动态组件结合keep-alive
  9. spring自定义自动配置注解
  10. docker基础知识普及(一)