Home > Mobile >  Click function inside for loop only effecting last iteration
Click function inside for loop only effecting last iteration

Time:09-13

I'm having an issue with the code below, the function is to find click on all links that contain ".gif". The code seems to iterate but only clicks the last iteration (when i=20), after some research it seems to be an issue with "hoisting" although Im unsure how to edit my code to fix the issue.

for (let i = 0; i < 20; i  ) {
    if (document.getElementsByTagName("a")[i].hasAttribute("href")) {

        if (document.getElementsByTagName("a")[i].getAttribute("href").includes(".gif")) {

            document.getElementsByTagName("a")[i].click();
        }
    }
}

CodePudding user response:

I don't see any obvious scoping/hoisting issues in your code, but there's no reason for repeated calls to get all elements just to take the i-th element and throw the rest away. Try making one selection, then .filter out the ones matching your predicate then .forEach the elements that passed the filter and click them. If you had any variable issues, using self-contained array functions should resolve the problem.

[...document.querySelectorAll("a[href]")]
  .filter(e => e.getAttribute("href").endsWith(".gif"))
  .forEach(e => e.click());
<a href="foo.gif">foo</a>
<a href="bar.gif">bar</a>
<a href="baz.png">baz</a>

The wildcard $ approach from Kinglish is better, but I'll leave this up for the explanation for now.

CodePudding user response:

Building off of @ggorlen's solution, you could further refine it using the wildcard $ css selector

document.querySelectorAll("a[href$='.gif']").forEach(e => e.click());
  • Related