Search code examples
javascriptgreasemonkey

Cannot programmatically click <a> tag in Greasemonkey script


I'm trying to get Greasemonkey in Firefox to click this anchor which doesn't have an href attribute:

<a class="btn btn-primary pull-right"
   ng-class="{'disabled': programsTabSubmitInProgress}"
   ng-click="handleAddProgramClick()">
  <i class="fa fa-plus"></i>
  <span>Add Program</span>
</a>

I already tried this line of code, but it won't work:

// ==UserScript==
// @name        Final Test
// @description Final test results
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// @include     https://qs-hub.qs.com/#/profiles/topuniversities/programs*
// ==/UserScript==
setTimeout(function () {
  document.querySelector('.btn.btn-primary.pull-right').click();
}, 5000);

Does anyone have the right solution to click this anchor?


Solution

  • The code should work fine. You do need to ensure that you click the right element:

    console.log(document.querySelector('.btn.btn-primary.pull-right'));
    

    As per the comments, you actually want to click the fifth such element. That'd be:

    document.querySelectorAll('.btn.btn-primary.pull-right').item(4).click();
    

    document.querySelectorAll returns a NodeList of which we click the fifth item.

     

    You are not using jQuery by the way, so there is no need to require that in your script.

    Instead of having the timeout, consider waiting for the page to load:

    window.addEventListener('load', function() {
        document.querySelectorAll('.btn.btn-primary.pull-right').item(4).click();
    }, false);