1

I have a chrome extension and i need JavaScript to click on this button, but it is not working.

This is the button that needs to be clicked with JavaScript.

<a class="button checkout" data-no-turbolink="true" href="...">checkout</a>

This is what I tried but it is not working

document.getElementsByClassName("button checkout").click();

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Denny callà
  • 115
  • 1
  • 6
  • I believe this question got answered here: https://stackoverflow.com/questions/25587762/javascript-click-on-element-by-class – Ahmed Mahmoud Mar 29 '21 at 19:39

3 Answers3

0

When you getting an element by class name it comes in form of an array with all of the elements having this class name, so you're trying to use .click() method on the array rather than an element. Consider switching from a class name to an id which would be unique just for that element.

<a id="button-checkout" data-no-turbolink="true" href="...">checkout</a>

document.getElementsById("button-checkout").click();
0

You need to specify the index

document.getElementsByClassName("button checkout")[0].click()

function clickme(){
  document.getElementsByClassName("button checkout")[0].click()
}

function clicked(){
  alert('It works!!!!!!')
}
<a class="button checkout" data-no-turbolink="true" href="www.google.com" onclick="clicked()">checkout</a>
<hr/>
<button onclick="clickme()">Click div</button>
0

I would give the button a unique idand instead of click() use an event listener.

HTML

<a class="button checkout" id="click_me" data-no-turbolink="true" href="...">checkout</a>

JS

document.getElementById('click_me').addEventListener('click', () => {
  //Your code here
})
BranOIE
  • 400
  • 4
  • 19