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 badges2 Answers
Reset to default 6getElementsByClassName
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?