Search code examples
javascriptjquerytampermonkey

Add a click to each array item


So my problem is that I would like the script to click on each class after it simply logged it in the console.

I've tried adding some .click() method after a few pieces of the code but no luck.

Here is the code below

var array = ['.button.color.color-41d841', '.button.color.color-dc0000', '.button.color.color-1e00e9', '.button.color.color-ff6f00'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function(el, index) {
  setTimeout(function() {
    console.log(el);
  }, index * interval);
});
console.log('Loop finished.');

It just prints the element's class.

Solved

var array = ['.button.color.color-41d841', '.button.color.color-dc0000', '.button.color.color-1e00e9', '.button.color.color-ff6f00'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function(el, index) {
  setTimeout(function() {
    console.log(el);
    $(el).click()
  }, index * interval);
});
console.log('Loop finished.');

Solution

  • try this, you need to find the element and click on it

    var array = ['.button.color.color-41d841', '.button.color.color-dc0000', '.button.color.color-1e00e9', '.button.color.color-ff6f00'];
    var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
    array.forEach(function (el, index) {
    setTimeout(function () {
    console.log(el);
    document.querySelector(el).click()
    }, index * interval);
    });