Này người xa lạ!

Còn chờ gì nữa mà không mau đăng nhập hoặc đăng ký để cùng tham gia thảo luận với cộng đồng!

Clicking multiple elements

I need a script to find all elements with the same class then click on specific ones of them.
I used var x= document.getElementsByClassName("Class Name"); to get a list of all elements with that class, but the script can only click on one of the elements.
If i add
The second element with that class will be clicked, but not the fourth. if I write it as
The fourth will be clicked but not the second.
if I change them to variables and put
var a=x[1]
var b=x[3]
The same thing happens
Adding timeouts also doesn't work
Same thing still happens
Using a loop also only clicks on the first element, but I can change other attributes, like text color, of every element.
Writing multiple scrips, one for each click, also doesn't work.
Putting the clicks together into one function with
Also doesn't work, but clicks the last element in the list instead of the first.
Why will only one .click(); run?
How can I click multiple elements?

Bình luận

  • đã sửa June 2018 Chrome

    Here you go:

    function trigger() {
        for(let el of arguments) el.click();
    var x = document.getElementsByClassName('class');
    trigger(x[0], x[2]); // it should click first and third element

    I don't know what is wrong in Your case, but in mine it works correctly. Can you send Your code?

  • đã sửa July 2018 Firefox

    setTimeout(x[3].click(),2000); needs to be setTimeout(x[3].click,2000);

    since you are passing a function and not the result of one.

    That wont help your click problem though since the page probably changes and the element in the collection may no longer be on the page or had been replaced with a new one that only looks the same.

    I am not recommending this for a final product

    document.getElementsByClassName("Class Name")[1].click();
    document.getElementsByClassName("Class Name")[3].click();

    This is just see if it behaves correctly.

    Lastly to make the function work you would need it like this


    you can even setTimeout((function(){x[1].click();x[3].click();}),2000);
    or setTimeout(() => {x[1].click();x[3].click();},2000);

    function clickThings(){

    This will not make the clicks work different though as they will always go in order and not at the same time.

    you can try

    var clickOne = x[1].onclick;
    var clickTwo = x[3].onclick;

    but chances are that the onclick function (if even set) references the sender and wont work;

  • The problem maybe cause from the website, you should read the js from the website source.

  • đã sửa July 2018 Chrome

    All was answered before (and until you post teh site, we may only guess what's going wrong). I'm here to comment this line:


    is equal to


    because parenthesis returns last result, that passes as context to .click() method.

Đăng nhập hoặc Đăng ký để gửi bình luận.