I have this button that opens a modal when it is clicked. I am trying to call the onclick function for the button via javascript instead of using the mouse.
I used the dom to get the element via classname and tried to call the onclick function but i couldn't figure it out.
var elements = document.getElementsByClassName("shopify-buy__btn");
for (i=0; i<elements.length; i++) {
if (elements[i].onclick) {
elements[i].onclick(); // Run the "onclick" function.
}
}
Here's the website with the button:
.onClick()is an event - it doesn't not create a click, it says "do this when a click happens here"elements[i].click();click()instead ofonClick(). However, going a step further, I would suggest you improve your codebase by not usingonclickattributes in your HTML. UseaddEventListener()to unobtrusively assign the event handlers in your JS.