最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Click all buttons on page with same class Javascript - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 12

You 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.

发布评论

评论列表(0)

  1. 暂无评论