John Doe John Doe - 1 month ago 12
HTML Question

Click on HTML element using JS

So basically I have a web page, and a couple of HTML buttons on it. On one of them I'd like to perform a mouse click. I know this button's class name, so basically I want to click on it by its class name. I know how to get the class name but I don't know how to click on this element, maybe there is a click function or something I don't know anything about.

I'm using

var element = document.getElementsByClassName('hidden-xs truncate');
element.Click();


but i don't know what to do next, how to perform the click, can you help me with that?

element.Click();
method doesn't work, I get the error:


element.Click is not a function

Answer

because there is a possibility that there are multiple elements with the class name hidden-xs truncate javascript automatically places the elements in an array.

you can auto click the button like this:

document.getElementsByClassName("hidden-xs truncate")[0].click();

or

var element = document.getElementsByClassName("hidden-xs truncate"); element[0].click();

note: the [0] gets the first index of the array, if there are multiple elements with the classes given it will perform a click only on the first element if you did [1] it would be the second and so forth.