2

Click error in the Chrome's Developer Tools console.

I've tried some solutions from here, but they don't seem to work in the Dev Tools. Probably they're only for web pages.

var inputs = document.querySelectorAll('button.class');

for (var i = 0; i < inputs.length; i++) {

   setInterval(function() {inputs[i].click()}, 2000);
}

What I'm waiting to happen is for the script to click all the class='class' buttons on (any) web page, one by one, starting with the first one found. What happens is nothing and the following error is displayed in the console:

Uncaught TypeError: Cannot read property 'click' of undefined.

Eugene provided the solution, see below for the scenario when the button has multiple class. PS this was not a duplicate.

RFX
  • 55
  • 5

2 Answers2

3

Eliminate var and put let instead inside your loop.

const inputs = document.querySelectorAll('button.class-name');

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

  setTimeout(function() {
    inputs[i].click()
  }, 1000 * i);

}

if you want to target elements with multiple classes selection criteria then use this (elements must contain both classes)

document.querySelectorAll('.className1.className2')

If you do this (which you do not want)

 document.querySelectorAll('.className1, .className2')

You will include elements which can contain only one of these classes

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
  • not working. it seems to click only the first 5-6 buttons again and again, but there are more on the page. – RFX Sep 15 '19 at 16:03
  • haven't seen the setInterval try setTimeout, if it clicks on 5-6 buttons then obviously others have another class – EugenSunic Sep 15 '19 at 16:33
  • It works fine, however I'm afraid I'm not done yet. What should I do if the button has multiple class, and I want only button with class1 AND class2 AND class3 clicked? If I use querySelectorAll('button.class1, button.class2, button.class3') it will also click buttons that have only one of these 3. I've tried using getElementsByClassName instead, but somehow it jumps and it clicks only one in two buttons (skips every other one). – RFX Sep 16 '19 at 16:20
  • you should do it like this ```document.querySelectorAll('.className1.className2') ``` – EugenSunic Sep 16 '19 at 17:13
  • @GotobuyStore check the updated answer – EugenSunic Sep 16 '19 at 17:17
  • 1
    thank you Sir. I finally got what I wanted to. – RFX Sep 17 '19 at 09:05
-1

You could try using forEach to iterate your NodeList:

var inputs = document.querySelectorAll('button.class');

inputs.forEach(input => {
    setInterval(function() {
      input.click()
    }, 2000)
})
Christian Carrillo
  • 2,751
  • 2
  • 9
  • 15