-1

If i click on a button, i want to trigger another button selected by class.

I wrote the following HTML:

<button onclick="document.getElementsByClassName("frame-16nsqo4").click()">Click</button>

3
  • document.getElementsByClassName will return an array,so invoke click will not work Commented Nov 29, 2022 at 10:01
  • You wrote that code and what happened? Commented Nov 29, 2022 at 10:02
  • Nothing happend. Commented Nov 29, 2022 at 10:02

2 Answers 2

0

As I wrote in the comment document.getElementsByClassName("frame-16nsqo4") will return an array,thus document.getElementsByClassName("frame-16nsqo4").click() will not work

you need to get the element rather than array

So change

<button onclick="document.getElementsByClassName("frame-16nsqo4").click()">Click</button>

to

<button onclick="document.getElementsByClassName("frame-16nsqo4")[0].click()">Click</button>
Sign up to request clarification or add additional context in comments.

2 Comments

Or .querySelector() which is in theory faster as it doesn't need to search the entire DOM as it can exit early as soon as it finds the first match, unlike getElementsByClassName which searches the entire DOM
@NickParsons Yeah,but OP needs to clarity his question with more details
0

Document.getElementsByClassName has the suffix getElements not getElement indicating that it's a collection/array

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

Use

document.getElementsByClassName("frame-16nsqo4")[0].click()

or better use

document.querySelector(".frame-16nsqo4").click()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.