Using NodeLists

本文探讨了DOM中NodeList、NamedNodeMap及HTMLCollection等集合的特性,特别是它们的实时更新特性。文章通过一个无限循环的例子,展示了如何正确地遍历这些集合以避免潜在的问题,并提供了一种安全的迭代方法。

  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:

1 var divs = document.getElementsByTagName("div"),
2       i,
3       div;
4 
5 for (i=0; i<div.length; i++){
6     div = document.createElement("div");
7     document.body.appendChild(div);
8 }

 

  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:

1 var divs = document.getElementsByTagName("div"),
2       i, 
3       len,
4       div;
5 
6 for (i=0, len=divs.length; i<len; i++){
7     div = document.createElement("div");
8     document.body.appendChild(div);
9 }

 

  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.

 

转载于:https://www.cnblogs.com/linxd/p/4521579.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值