zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Difference between getElementBy series and querySelector series

The usage of querySelector and querySelectorAll is similar to getElementBy, with the addition of symbols when retrieving elements. getElementBy retrieves a dynamic collection of elements, while querySelector retrieves a static collection of elements.

However, it is important to note the difference between the getElementBy series and the querySelector series.

For example, let's write a for loop that generates an li child element for ul each time it retrieves the li tag.

<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 an infinite loop
</script>

Using i < li.length as the condition will cause the browser to enter an infinite loop because each time the loop runs, the browser re-retrieves the li tag array. Each call will re-query the document, resulting in an infinite loop.

To fix this, change i < li.length to i < 3, staticize the li tag array, and then print the result.

console.log(li.length)  // 6

Re-retrieve 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
</script>

The static collection is reflected in querySelectorAll('li'), which retrieves all li tags inside ul. Regardless of how many li elements are dynamically added later, it will not affect the retrieved collection.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.