Is it dangerous to use for loop in querySelectorAll?

Asked

Viewed 118 times

0

Always when I need to select more than one element on a page it is not possible to use the querySelector() isn’t it? Then we should resort to querySelectorAll(). I’ve always used it the following way (img is just a hypothetical example):

img = document.querySelectorAll("img");
for (var i = 0; i < img.length; i++) {
    console.log(img[i]);
}

But the other day in an argument with a friend, we come to an impasse, what if there are too many elements on a page? Couldn’t this cause problems for users who have slower computers? Something like an infinite loop does..

There is another way to interact with various elements with the same genre without having to worry if it will not end up disturbing my user’s navigation?

  • It depends on what you do within the for cycle, but this is the "normal" way to iterate lists of elements. You can write html with classes or using selectors with relatives to make the smallest selection.

3 answers

4

If you need to do something with all elements that match a given selector, the only way is to loop over the list of these elements (be it obtained with the querySelectorAll or by some other method, such as getElementsByTagName).

Therefore, if there are too many elements being selected and this is generating slowness in processing, it is necessary to rethink what you are doing, to avoid having to select all these elements, or at least avoid being manipulated at the same time. But this will only be a problem if you notice a real performance problem in a usage considered "standard" of the site or app (which includes access using a "standard" machine, a "standard" browser and a "standard" connection). My general recommendation in your case: avoid premature optimizations.

  • Great: avoid premature optimizations

3


It’s safe to use the for

however it is necessary to pay attention to the performance.

The foreach is by far the worst option for finding out about an Array, the FOR, as mentioned is a much better option but the way it will be made impact a lot, follows a link where you can test this performance yourself

http://jsperf.com/for-vs-foreach/37

For my case the results were as follows:

foreach

values.forEach(add);

operations per second: 1,327

for loop, simple

for (i = 0; i < values.length; i++) {
    sum += values[i];
}

operations per second: 10,559

for loop, cached length

length = values.length;
for (i = 0; i < length; i++) {
    sum += values[i];
}

operations per second: 10,584

for loop, Reverse

for (i = values.length - 1; i >= 0; i--) {
    sum += values[i];
}

operations per second: 10,530

2

Yes, is safe.

Obviously, there will always be a chance that the client’s computer will take too long to process an instruction, but in this case, it is not a valid concern.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.