How to call an existing onclick function using javascript

93 views Asked by At

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:

https://fantastic-choice-042131.framer.app/

1

There are 1 answers

2
Discorduser200 On

I belive what you are trying to do is:

var elements = document.getElementsByClassName("shopify-buy__btn");
for (i = 0; i < elements.length; i++) {
    elements[i].click(); // Run the "onclick" function by simulating a click.  
}

Although it is probably not the optimal way to do this. See the comments.