user17874000
user17874000

Reputation: 11

how to automate pressing a button on a website

I need to write a JavaScript program that clicks buttons on a site for few times. I tried to wrote it, but it click only one time and then stops.

let button = document.querySelector("path to the button");
for (let i = 0; i < 5; i++) {
    button.click();
}

Upvotes: 1

Views: 73

Answers (2)

Julien Machin
Julien Machin

Reputation: 51

You can do a getElementById and give an id at your button like this

<button id="nameyouwant" />

I guess you gave a wrong name.

Upvotes: 0

Ran Turner
Ran Turner

Reputation: 18156

I assume the problem is that the "path to the button" is wrong. When you use querySelector you need to specify a valid css selector.

Checkout my example below

function doJobs(){
  let button = document.querySelector("#btn");
  for (let i = 0; i < 5; i++) {
      button.click();
  }
}

function sayHi(){
  alert("hi")
}
<button id="btn" onclick="sayHi()">
 click me
</button>

<button onclick="doJobs()">
 doJobs
</button>

Upvotes: 1

Related Questions