So they always have the latest and most accurate information. Essentially, all NodeList objects are queries that run in real time when accessing a DOM document. For example, the following code will cause an infinite loop:
First get the page For all divs in the div, since this collection (divObj) is "dynamic", whenever a new div is inserted into the page, divObj will add the newly added div. In other words, as long as divObj is accessed, it will be queried again and divObj will be updated again. Therefore, the above code will cause an infinite loop, because a new div is inserted during each loop, and each loop must evaluate the condition i
.
If you want to iterate over a NodeList, it is best to initialize a second variable using the length property and then compare the iterator to that variable. As shown in the following code:
In this example the second variable (len) is initialized. Since len stores a snapshot of divObj.length at the beginning of the loop, the infinite loop in the previous example will be avoided.
Summary: Generally speaking, the number of visits to NodeList should be minimized. Because every time a NodeList is accessed, a document-based query is run. Therefore, you can consider caching the values obtained from NodeList, as shown in Example 2!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn