As a result, they always keep 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 can cause an infinite loop:
Copy Code code 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 get all the div on the page, because this set (Divobj) is "dynamic", so whenever a new div is inserted into the page, Divobj adds the newly added Div. In other words, as long as access to Divobj, will requery, update divobj. So, the above code, there will be a dead loop, because each time the loop is inserted a new div, and each loop to the condition i<divobj.length evaluation, meaning that will run the obtained all <div> queries.
If you want to iterate over a nodelist, it is best to use the Length property to initialize the second variable and then compare the iterator with that variable. As shown in the following code:
Copy Code code 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. Since Len holds a snapshot of the divobj.length at the beginning of the loop, the dead loop of the previous example is avoided.
Summary: In general, the number of visits to nodelist should be minimized. Because every time you access nodelist, you run a document based query. So, consider caching the values you get from nodelist, as shown in example two!