Click button via pure javascript

2

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

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

    
asked by anonymous 30.07.2014 / 04:20

2 answers

4

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

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

Or using querySelectorAll :

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

More about the click() method: HTMLElement.click

    
30.07.2014 / 14:19
2

To click a button "programmatically" on a button you must call the onclick of the element. You can do this:

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

Example: link

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

    
30.07.2014 / 11:10