Skip to content Skip to sidebar Skip to footer

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). Howeve

Solution 1:

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:

<buttonclass="a"></button><buttonclass="a b"></button><buttonclass="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()

Solution 2:

  1. Remove the .'s

  2. The function returns an array-like object, a hint is in the name as it is plural so you have to specify a key in the array.

HTML

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

JavaScript

document.getElementsByClassName('btn btn-danger btn-lg  btn-block betButton')[0].style.backgroundColor = 'red';

Example

JSFiddle

Note...

As can be seen in this example, you need to remove the . for it work, as JavaScript already knows you are selecting classes through the function you are using.

Using querySelector

JavaScript

document.querySelector('.btn-danger.btn-lg.btn-block.betButton').style.backgroundColor = 'red';

Example

JSFiddle

Post a Comment for "Click() Command Not Working On Document.getelementsbyclassname()"