The usage of querySelector
and querySelectorAll
is similar to getElementBy
, where symbols are used to retrieve elements. However, there is a difference between getElementBy
series and querySelector
series.
For example, let's write a for loop that generates a new li element for each iteration when retrieving the li tags from ul.
<ul id="ul">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
<script>
var ul = document.getElementById('ul');
var li = document.getElementsByTagName('li');
for(var i = 0;i < li.length; i++) {
ul.appendChild(document.createElement('li'))
};
console.log(li.length);
// Enters into an infinite loop
</script>
Using i < li.length
as the condition for the loop will cause the browser to enter an infinite loop. This is because each time the loop is executed, the browser retrieves the li tag array again, resulting in a continuous query of the document and entering an infinite loop.
To fix this, modify the condition from i < li.length
to i < 3
to statically define the li tag array, and then print the result.
console.log(li.length) // 6
Re-fetch the elements using querySelector
<ul id="ul">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
<script>
var ul = document.querySelector('ul');
var li = document.querySelectorAll('li');
for(var i = 0;i<li.length;i++) {
ul.appendChild(document.createElement('li'))
};
console.log(li.length);
// The output is the original li.length = 3, not the increased 6 after adding new li elements
</script>
The static collection is reflected in querySelectorAll('li')
. Once it retrieves all the li elements inside ul, it will not be affected by any subsequent dynamic additions of li elements.