0

In my Chrome extension, I have an array of anchor tags (from the DOM) which are the links of downloadable files and I'm clicking on them in the loop using .click(), but only the last link is clicked. I used setTimeout, but it's clicking only the last element.

I checked my console; even with setTimeOut it prints the values all together at once.

setTimeout(() => {
  let rows = document.getElementsByClassName('jz-table is-bordered-horizontal')[1].rows
  for (let i = 1; i < rows.length; i++) {
    setTimeout(() => {
      console.log(i)
      if (typeof rows[i].querySelectorAll("a[ng-switch-when=Download]")[0] != "undefined") {
        console.log(rows[i].querySelectorAll("a[ng-switch-when=Download]")[0])
        rows[i].querySelectorAll("a[ng-switch-when=Download]")[0].click()
      }
    }, 2000);
  }
}, 2000);
Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
Faizan Ahmed
  • 184
  • 3
  • 12

1 Answers1

0

The problem with this code as I can see is in the indexing of arrays. Before you fix anything else,

    let rows=document.getElementsByClassName("yourClass")[0].rows

will give you all the rows of the table, not [1] unless there is a table before it you have skipped.

Then,

    for (let i=0; i<rows.length; i++){

is the correct way to index the loop, unless you want to skip rows[0]. After that is corrected, then, let's see what else needs to be fixed!

That may not be the problem, but see this link for the problems with calling setTimeout() from within a loop: https://coderwall.com/p/_ppzrw/be-careful-with-settimeout-in-loops