Remember the DOM APIs
document.getElementsBy*? When these methods are used, it is common to use a for loop to go through each element to perform some task. Even though the result of these methods can be treated like Arrays they are not arrays. What they are is an HTML collection. The power and main difference between these and a regular array is that they are directly tied to the DOM. If you update the DOM, the collection is updated accordingly.
Here is one little experience. We are going to create a live collection, and watch it update without any explicit interaction on our part.
var collection = document.getElementsByClassName("collection");
Let's say I declare this variable and there are no elements with class name 'collection'. Obviously, this will return an empty array like collection. If I check the length, it will be zero
console.log(collection.length); > 0
Now let's create an element with said class name and append it to the DOM and see what happens to our collection.
var element = document.createElement("p"); element.className = "collection"; document.body.appendChild(element); // Checking the length console.log(collection.length); > 1 console.log(collection); > <p class="collection"></p>
The new element found its way into our collection array without having to re-fetch it from the DOM.
This neat little feature can be very useful. You can have a variable that keeps track of, let's say, active users without having to constantly check the DOM or having to pop values in and out of an array.
I don't understand why getElementBy* are faster than querySelector when they traverse the DOM every single time as live collections typically do?
Ibrahima Diallo :
When it comes to performance, the difference between the two is negligible. Internally, they do the same thing. Except,
querySelectorhas a more complicated parsing rules which might make it slower.
One way to optimize is to avoid accessing the DOM inside a for loop, and to pre-fetch elements and save them in a variable to use them later.
Let's hear your thoughts