简体   繁体   中英

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

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM