简体   繁体   中英

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();

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:

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

class of my button is "input-addon btn btn-default fileinput-exists"

below code helped me

document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();

but I want to click second button, I have two buttons in my screen so I used querySelectorAll

var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
                elem[1].click();

here elem[1] is the second button object that I want to click.

for exactly what you want (if you know the index of button):

var rate = document.getElementsByClassName('rateRecipe btns-one-small')[0];
rate.click();

or for direct action

document.getElementsByClassName('rateRecipe btns-one-small')[0].click();

with jQuery

$('.rateRecipe .btns-one-small').click(function(){
    var vIndex = $('.rateRecipe .btns-one-small').index(this);
    //vIndex is the index of buttons out of multiple
    
    //do whatever 
    //alert($(this).val());//for value
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM