Click() Command Not Working On Document.getelementsbyclassname()
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 aHTMLCollection
with all the elements with classa
:[<button class="a"></button>, <button class="a b"></button>]
document.getElementsByClassName('a b')
will return aHTMLCollection
with all the elements with classesa
andb
:[<button class="a b"></button>]
document.getElementsByClassName('a.b')
will return aHTMLCollection
with all the elements with classa.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:
Remove the
.
'sThe 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
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
Post a Comment for "Click() Command Not Working On Document.getelementsbyclassname()"