Javascript Click an item by class

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

 var classes = document.getElementsByClassName('rateRecipe btns-one-small'); var Rate = classes[0]; Rate.click(); 
+6
source share
1 answer

I would suggest:

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

The code above assumes that this element has both of these classes; otherwise, if space should imply a parent-child relationship:

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

The getElementsByClassName() method accepts one class name (not document.querySelector() / document.querySelectorAll() , which accepts a CSS selector), and you passed this method to two (presumably class names).

Literature:

+17
source

Source: https://habr.com/ru/post/974596/


All Articles