How to perform a click() using Google Chrome's Console? (Javascript) - Stack Overflow

I am trying to make a Javascript code that automates a button click on a webpage, so I am trying to fig

I am trying to make a Javascript code that automates a button click on a webpage, so I am trying to figure out the code with Google Chrome's Console. This is the button:

<a href="#" class="link">Get Link</a>

I thought I could simply write this:

var button = document.getElementsByClassName('link');
button.click()

But this message appears:

"Uncaught TypeError: button.click is not a function at <anonymous>:2:8"

Any solution? Thanks for the help.

I am trying to make a Javascript code that automates a button click on a webpage, so I am trying to figure out the code with Google Chrome's Console. This is the button:

<a href="#" class="link">Get Link</a>

I thought I could simply write this:

var button = document.getElementsByClassName('link');
button.click()

But this message appears:

"Uncaught TypeError: button.click is not a function at <anonymous>:2:8"

Any solution? Thanks for the help.

Share Improve this question asked Jun 3, 2019 at 15:03 Javier CalvoJavier Calvo 391 gold badge1 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

getElementsByClassName returns a live HTMLCollection, not a single element.

elements is a live HTMLCollection of found elements.

So if you want to use getElementsByClassName, you need to get the first item from the iterable like this:

var button = document.getElementsByClassName('link');
button[0].click()

If you want to get a single element, use document.querySelector(). This will return the first found element.

var button = document.querySelector('.link');
button.click()

This is a screenshot of the line I wrote

Is it correct?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744100212a4558501.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信