简体   繁体   中英

Click function inside for loop only effecting last iteration

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();
        }
    }
}

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM