Javascript按类单击元素 [英] Javascript Click on Element by Class
问题描述
因此,我正在编写一个可以在页面上运行的脚本,但是我想单击此元素,但是不幸的是,它没有要获取的 id
,我正在尝试使用 .click()
函数,但是它不起作用,这就是我所拥有的,有人知道如何解决吗?这也是该类中唯一的元素
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();
推荐答案
我建议:
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();
方法 getElementsByClassName()
采用单个类名(而不是 document.querySelector()
/ document.querySelectorAll()
,使用CSS选择器),然后将两个(大概是类名)传递给该方法.
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.
参考:
这篇关于Javascript按类单击元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!