Is it dangerous to use for loop in querySelectorAll?

0

Whenever I need to select more than one element on a page, I can not use querySelector() , right? Then we must use querySelectorAll() . I've always used it as follows (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 have come to a standstill, and if there are too many elements on a page? Could not this cause problems for users who have slower computers? Something of the sort an infinite loop does ..

Is there another way to interact with multiple elements with the same genre without having to worry if this will not end up disrupting my user's browsing?

    
asked by anonymous 28.07.2014 / 22:12

3 answers

3

It is safe to use the

But you have to watch for performance.

The forEach is by far the worst option to find out about an Array, the FOR, as it was quoted is a much better option however the way it will be done impacts a lot, follow a link where you can test this performance yourself

link

In 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

    
28.07.2014 / 22:44
4

If you need to do something with all elements that match a particular selector, the only way is to loop over the list of those elements (either querySelectorAll or some other method, such as getElementsByTagName ) .

So if too many elements are being selected and this is slowing down processing, you have to rethink what you are doing, to avoid having to select all of these elements, or at least to avoid being manipulated all at the same time. But this will only be a problem if you perceive a real performance problem in a "standard" use 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.

    
28.07.2014 / 22:25
2

Yes, is safe .

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

    
28.07.2014 / 22:20