Add an id to the above button with a onClick function.
Change the
document.getElementsByName('name')
to
document.getElementById('id')
Full Code:
Html:
<button id="btn" 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 class="btn" 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.