I want to automatically trigger a tap on a button with javascript.
var submitButton = document.getElementsByName('name');I tried the following and none of them worked.
submitButton.click();and
const touchEvent = new TouchEvent("touchstart", { touches: [touch], view: window, cancelable: true, bubbles: true,
});
submitButton.dispatchEvent(touchEvent);Neither worked.
43 Answers
Document.getElementsByName() returns a NodeList of elements (not a single element).
As far as the event, click should work just fine:
for (const elm of document.getElementsByTagName('button')) { elm.addEventListener('click', (ev) => console.log(ev.target.textContent));
}
const buttons = document.getElementsByName('name');
for (const button of buttons) { button.click();
}<div> <button name="name">one</button> <button name="name">two</button> <button>three</button>
</div> Add an id to the above button with a onClick function. Change the
document.getElementsByName('name')to
document.getElementById('id')Full Code:
Html:
<button onClick="clicked()">
Click me
</button>JS:
var btn=document.getElementById("btn");
btn.click();
function clicked() { console.log("Clicked");
}If you want to trigger multiple buttons with same class:
Html:
<button onClick="clicked()">
Click me
</button>JS:
var btn=document.getElementsByClassName("btn");
btn[0].click();
function clicked() { console.log("Clicked");
}For multiple button with same class, the return of the document.getElementsByClassName will return an array of object. In the above example, I have used the first element of that array, but if you want, you can loop through the array and trigger the click event.
document.getElementsByName returns a NodeList Collection of elements with a given name attribute in the document.
So your submitButton will be an array. So you have to dispatch the click event with submitButton[0].click()
var submitButton = document.getElementsByName('name');
submitButton[0].click();
function submitClick() { console.log('submitClick')
}<button name="name" onclick="submitClick()">Submit</button>