Click a button through Class

4

I have the following button:

<button class="btn btn-danger btn-lg  btn-block betButton">Submit</button>

And I would like to do a click on it through an event in javascript, but that's what to give me the following error: Uncaught TypeError: l.click is not a function (...)

Code I use:

var l = document.getElementsByClassName('btn btn-danger btn-lg  btn-block betButton');
l.click();
    
asked by anonymous 25.05.2016 / 17:58

1 answer

6

When you use the getElementsByClassName selector, the result will be an array with all the elements that contain this class, so to fix the error, you just need to set an index, for example l[0] , however, assign the event to only one item, ideally use the id attribute and retrieve the element with the getElementById function.

But you have another error in your code, to assign an event to the element, you need to use the addEventListener function, the way you did, with click() , will only simulate the event in the element. See below for a working example.

var l = document.getElementsByClassName('btn btn-danger btn-lg btn-block betButton');
l[0].addEventListener('click', function() {
  alert('teste');
});
<button class="btn btn-danger btn-lg btn-block betButton">Submit</button>
    
25.05.2016 / 18:04