Click all buttons on page with same class Javascri

2020-03-06 05:21发布

问题:

I'm trying to click all buttons on a page with the class "btn btn-primary UnFollowUser".

Here is the script I have tried using

var buttons = document.getElementsByName('UnFollowUser');

for(var i = 0; i <= buttons.length; i++)  
   buttons[i].click();

But that throws the error:

VM336:5 Uncaught TypeError: Cannot read property 'click' of undefined(…)(anonymous function) @ VM336:5InjectedScript._evaluateOn @ VM158:878InjectedScript._evaluateAndWrap @ VM158:811InjectedScript.evaluate @ VM158:667

Any ideas?

回答1:

You are using getElementsByName instead of getElementsByClassName

 var buttons = document.getElementsByClassName('UnFollowUser');

 for(var i = 0; i < buttons.length; i++)  
     buttons[i].click();


回答2:

I got a similar error for some reason (and yes I was using getElementsByClassName). For some reason using a "while (buttons.length != 0)" instead of a "for (var i = 0; i < buttons.length; i++)" fixed the issue.

 var buttons = document.getElementsByClassName('nameOfClass');

 while(buttons.length != 0)  
     buttons[i].click();

I believe the reason why this worked is that for some reason the button's array updated each time a button was destroyed: so when the loop is on the 5th of 5 buttons, i = 5, but buttons.length = 5 so it would terminate prematurely.