Click a button through Class

Asked

Viewed 205 times

4

I have the following button:

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

And I’d like to make one click in it through a javascript event, only that is giving 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();

1 answer

6


When you use the selector getElementsByClassName, the result will be an array of all elements containing this class, so to correct the error, you only need to define an index, for example l[0], however, if you will assign the event to only one item, the ideal is to use the attribute id and retrieve the element with the function getElementById.

But there is another error in your code, to assign an event to the element, you need to use the function addEventListener, the way you did, with the click(), will only simulate the event in the element. See below for a functional 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.