Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Click on Element by Class

So I am writing a script that can be run on a page but I want to click on this element, unfortunately, it does not have an id to get and I am trying to use the .click() function on it, but it doesn't work, here's what I have, anyone know how to fix it? This is the only element in the class also

var classes = document.getElementsByClassName('rateRecipe btns-one-small'); var Rate = classes[0]; Rate.click(); 
like image 730
Cup of Java Avatar asked Aug 30 '14 23:08

Cup of Java


People also ask

How do you click an element in JavaScript?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

Can you AddEventListener to a class?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class.


1 Answers

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click(); 

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click(); 

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

  • document.getElementsByClassName().
  • document.querySelector().
like image 175
David Thomas Avatar answered Sep 29 '22 09:09

David Thomas