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?
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?
Share Improve this question edited Mar 17, 2016 at 14:36 The Process 5,9533 gold badges32 silver badges41 bronze badges asked Mar 17, 2016 at 14:28 SavantSavant 311 gold badge1 silver badge3 bronze badges 3-
1
Did you mean
getElementsByClassName('UnFollowUser');
– The Process Commented Mar 17, 2016 at 14:30 - Are you using jQuery or not? – xkcd149 Commented Mar 17, 2016 at 14:30
- @itsgoingdown ah, that fixed it! – Savant Commented Mar 17, 2016 at 14:32
2 Answers
Reset to default 12You are using getElementsByName instead of getElementsByClassName
var buttons = document.getElementsByClassName('UnFollowUser');
for(var i = 0; i < buttons.length; i++)
buttons[i].click();
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.