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!