0

I am trying to trigger this button using javascript but I am having no luck. I have tried using getElementsByClassName but it is not working, what am I doing wrong?

<html>
<body>
<button onclick="test();"> Click</button>
<input type="button" name="vote" value="   Vote   " class="Buttons" onclick="result();" />
<script>
function result(){
document.write("test");
}
function test(){
document.getElementsByClassName("Buttons").click();
}
</script>
</body>
</html>

  • As any javascript reference should have pointed out `getElementsByClassName` returns an array of matching tags, you can't call `click` directly. – Pierre Feb 11 '20 at 19:18
  • https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return – j08691 Feb 11 '20 at 19:19
  • How would I go about clicking it then? – basicuser07 Feb 11 '20 at 19:19
  • 2
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Pierre Feb 11 '20 at 19:19

1 Answers1

1

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class names. You need to loop through this array of matched elements and call the click function.

var elements = document.getElementsByClassName('Buttons');

for (var i=0;i<elements.length; i++) {
    elements[i].click();
}

OR

for(element of elements) {
    element.click()
}
varoons
  • 3,807
  • 1
  • 16
  • 20
  • 1
    How about explaining your solution? – j08691 Feb 11 '20 at 19:22
  • your code calls click on all matching tags, this is not really what the user wants. He will have only one element found. He just have to index the array returned by `getElementsByClassName` with the first index : `elements[0].click()` (after having checked elements[0] exists) – Pierre Feb 11 '20 at 19:24
  • This is just a general solution. He can figure it out from here. – varoons Feb 11 '20 at 19:25