How to find multiple elements on headless browser and click them after a timeout

275 Views Asked by At

I want to detect elements in the DOM without a specific child, and then click the ones without the child after a timeout. There is no way to explicitly and directly find the elements only get all elements with a certain class, and omit the ones with a specific child class.

Let's say the browser has this code:

<div class="card">
  <div></div>
  <button>
</div>
<div class="card">
  <div></div>
  <button>
</div>
<div class="card">
  <div class="dont-click"></div>
  <button>
</div>

The following code works in casperjs/horseman, basically gets all elements with the .card class then looks for elements where a child has the .dont-click class and omits it:

  var cards = $('.card');
  var listOfClickables = cards.filter(function(i, card) {
    var jCard = $(card);
    var found = jCard.find('.dont-click');
    if (found.length <= 0) {
      return jCard;
    }
  });

  return listOfClickables;

This works, now I want to go through this list, one by one, and click the child button of each .card. This code works if you copy and paste into the browser:

recursiveFunction(listOfClickables);
function recursiveFunction(list){
  var jCard = list.shift();
  $(jCard).find('button').click();

  var delayMs = Math.random() * 5;

  setTimeout(function() {
    recursiveFunction(list);
  }, delayMs * 1000);
}

It takes the list from the previous function, and recursively clicks the child button, waits a bit, and then pops the next element until the list is empty.

I tried to click just a single one of these items but I'm running into some problems:

  1. Seems like everything must be done in the .evaluate() block, you can't return a list of jquery elements, and then pass it into another .evaluate() block
  2. Seems like you can't click the element using a jQuery.click('.card button'), you'd have to somehow identify it outside of the .evaluate() block, and then use the .click() method from casperjs/horseman.

Is it possible to use these frameworks to do something like a "find all elements with this selector, and then go through these elements and return the ones without a child element with class .dont-click, then click all the returned elements' child buttons"?

0

There are 0 best solutions below