admin 管理员组

文章数量: 1086019

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?

本文标签: How to perform a click() using Google Chrome39s Console (Javascript)Stack Overflow