Click on a button via pure javascript

Asked

Viewed 17,274 times

3

I need to create some simple script where it looks for a class inside the page and whenever it finds such a class (this is always a button) the button referring to it should be clicked.

Could you help me with some example of this in pure Javascript?

  • If you look for a button for the class, it will click on each button in case there is more than one. That’s what you want?

2 answers

5


To simulate a click on an element, just use the method click() of the same.

var botoes = document.getElementsByTagName("button");
for (var i = 0; i < botoes.length; i++) {
    if (botoes[i].className === "MINHA-CASSE") {
        botoes[i].click();
    }
}

Or using the querySelectorAll:

var botoes = document.querySelectorAll("button.MINHA-CLASSE");
for (var i = 0; i < botoes.length; i++) {
    botoes[i].click();
}

More about the method click(): Htmlelement.click

2

To click "programmatically" on a button you have to call the onclick of the element. You can do it like this:

var botoes = document.querySelectorAll('button.tal_classe');
for (var i = 0; i < botoes.length; i++) botoes[i].onclick.apply(botoes[i]);

Example: http://jsfiddle.net/9Kx2t/

You can also use the .call(). The important thing here is to pass the botoes[i] for the onclick as this.

  • Someone gave -1 in my reply. Comments are welcome :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.