DEV Community

Jesse
Jesse

Posted on • Updated on

Use JavaScript to click a button for you

So let's say you have a button on your website that you want to click a bunch of times for completely ethical purposes..

I'm going to show you how to do just that with 8 lines of code.

Let's get started

Write a function

function myFunction() {

}
Enter fullscreen mode Exit fullscreen mode

Select the button and assign to variable

There are going to be two ways to do this.

Select by ID

var button = document.getElementByID('mybutton');

Select by Class

var button = document.getElementsByClassName('mybutton')[0];
In this example above, I select the first element using the class name specified using [0].

Checking in

Your code should look like this now:

function myFunction() {
    var button = document.getElementByID('mybutton');
}
Enter fullscreen mode Exit fullscreen mode

For loop

Next thing to do is setup a for loop. I could easily write a whole post on these but here's the syntax and a quick breakdown:
for (i = 0; i < 20; i++) {

Start the loop at 0. Run it as long as i is less than 20. Increment by 1 each time it loops.

Click the button

Finally, inside your for loop, you can tell your function to click the button using .click().
button.click();

End result

function myFunction() {
    var button = document.getElementByID('mybutton');
    for (i = 0; i < 20; i++) {
        button.click();
    }
}
// Run the function:
myFunction();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)