Notes for using NodeList in javascript

Source: Internet
Author: User

Therefore, they always store the latest and most accurate information. Essentially, all NodeList objects are queries that run in real time when accessing DOM documents. For example, the following code causes an infinite loop:

Copy codeThe Code is as follows: <script type = "text/javascript">
Window. onload = function (){
Var divObj = document. getElementsByTagName ('div ');
For (var I = 0; I <divObj. length; I ++ ){
Var d = document. createElement ("div ");
Document. body. appendChild (d );
}
}
</Script>

First, obtain all the divs on the page. Since this set (divObj) is "dynamic", divObj will add this newly added div as long as a new div is inserted into the page. That is to say, as long as divObj is accessed, it will be re-queried and updated again. Therefore, the code above will have an endless loop, because a new div is inserted during each loop, and each loop requires the condition I <divObj. evaluate the length, which means that the query of all obtained <div> is run.

If you want to iterate A NodeList, it is best to use the length attribute to initialize the second variable, and then compare the iterator with the variable. The following code is used:

Copy codeThe Code is as follows: <script type = "text/javascript">
Window. onload = function (){
Var divObj = document. getElementsByTagName ('div ');
For (var I = 0, len = divObj. length; I <len; I ++ ){
Var d = document. createElement ("div ");
Document. body. appendChild (d );
}
}
</Script>

In this example, the second variable (len) is initialized ). As len stores a snapshot of divObj. length at the beginning of the cycle, it will avoid the endless loop in the previous example.

Conclusion: In general, we should minimize the number of NodeList accesses. Because every time you access NodeList, a document-based query is run. Therefore, you can consider caching the value obtained from NodeList, as shown in example 2!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.