Savant
Savant

Reputation: 31

Click all buttons on page with same class Javascript

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?

Upvotes: 3

Views: 17335

Answers (2)

notansandwich
notansandwich

Reputation: 69

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.

Upvotes: 0

User K
User K

Reputation: 380

You are using getElementsByName instead of getElementsByClassName

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

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

Upvotes: 12

Related Questions