[Solved] click() command not working on document.getElementsByClassName()


getElementsByClassName returns a HTMLCollection, which is an array-like object.

That means that in you case, you should get the element at index 0, which ideally for the kind of application that you are building should be the only one that you get:

document.getElementsByClassName('btn btn-danger btn-lg btn-block betButton')[0].click()

Otherwise your extension will probably stop working if the websites gets updated and the elements that matches your selector change order.

Note also that as @Barmar pointed out, to filter by multiple classes with getElementsByClassName you should use spaces, not dots.

Let’s say you have:

<button class="a"></button>
<button class="a b"></button>
<button class="a.b"></button>

Then:

  • document.getElementsByClassName('a') will return a HTMLCollection with all the elements with class a: [<button class="a"></button>, <button class="a b"></button>]
  • document.getElementsByClassName('a b') will return a HTMLCollection with all the elements with classes a and b: [<button class="a b"></button>]
  • document.getElementsByClassName('a.b') will return a HTMLCollection with all the elements with class a.b: [<button class="a.b"></button>]

You can use querySelectorAll to be able to use selectors like .a.b or just querySelector, which instead of a HTMLCollection will return just the first element that matches the selector, so you can call click on it straight away:

document.querySelector('.btn.btn-danger.btn-lg.btn-block.betButton').click()

0

solved click() command not working on document.getElementsByClassName()