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?
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?
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
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
.