0

I'm a beginner is learning how to code for Tampermonkey. I know how to click an automated clicking using a class tag or id tag. But is there anywhere to automate a clicking based on data info such as data-id, name or image URL?

The HTML is like:

<div class="yellow-bot" data-image="//imgurl1.gif" data-id="123" data-name="Image1">...</div>
<div class="yellow-bot" data-image="//imgurl2.gif" data-id="124" data-name="Image2">...</div>
<div class="yellow-bot" data-image="//imgurl3.gif" data-id="125" data-name="Image3">...</div>
...
...
...
<div class="submitButton">
<input id="button" type="submit" value="Submit Now" class="btn-primary">
</div>

So I'd like the click to click id 124 and 125 but the class is all the same. and then click on the Submit button. Can anyone help me with this?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Reeves
  • 9
  • 1

1 Answers1

1

Reference CSS selectors and jQuery selectors.

So, selecting by attribute:

document.querySelector (".yellow-bot[data-id='124']").click ();
document.querySelector (".yellow-bot[data-id='125']").click ();

Or much more robustly:

// ==UserScript==
// @name     _Click nodes by attribute
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */

waitForKeyElements (".yellow-bot[data-id='124']", clickNode, true);
waitForKeyElements (".yellow-bot[data-id='125']", clickNode, true);

function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}


For the rest, see Choosing and activating the right controls on an AJAX-driven site.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295