SamZi SamZi - 3 months ago 52
Javascript Question

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

Im making automated browser scripts with javascript and I want to use the click() command on this website but the button on the website doesnt have an Id (which works fine). However it only has a class name. When I do

document.getElementsByClassName(btn.btn-danger.btn-lg.btn-block.betButton).click()
it doesnt work.

Here is the inspect of the button I want to click:

<button class="btn btn-danger btn-lg btn-block betButton" data-color="r">1 to 7, Win x2</button>


Is it possible to use the click() function on the button? Is there someway to assign an Id myself? Thanks for any answers :)

I dont think that is a copy as I know what differences are. But the button doesnt have any Id only a class name. And as that doesnt work what else could I do to trigger a click() event?

Edit2 = There is 3 buttons with all the same class names the only difference is the text of the button and the data-color, is there any way to manipulate that?

Answer

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()