1

I have written a javascript and injecting it via a chrome extension such as Tamper Monkey. I find all the tags and then change it to a button but I am not able to make the click work. My page has some text called "Approver". I replace that with a button with the same text "Approver" and it shows as a button, but when I click it, the function ptmTest is not getting called. Below is part of the Javascript code that I am using to try and make this work. Any help on what I am doing wrong is greatly appreciated.

function ptmButton() {
  var x         = document.querySelectorAll( "dt" );
  var ptmButton = `<button class="aui-buttons trigger-label" onClick="ptmTest()">Approver</button>`
  var i;
  for ( i = 0; i < x.length; i++ ) {
    if ( x[i].innerText == "Approver" ) {
      x[i].innerHTML = ptmButton;
    }
  }

  function ptmTest() {
    console.log( "PTM clicked" )
  }
}

1 Answer 1

2

There are 2 solutions:

you can put the function ptmTest outside ptmButton:

function ptmButton() {
    var x = document.querySelectorAll( "dt" );
    var ptmButton = `<button class="aui-buttons trigger-label">Approver</button>`
    var i;
    for ( i = 0; i < x.length; i++ ) {
        if ( x[i].innerText == "Approver" ) {

            x[i].innerHTML =
                ptmButton;
        }
    }

}

function ptmTest() {
    console.log( "PTM clicked" )
}

you can also set the onClick in the script:

function ptmButton() {
    var x = document.querySelectorAll( "dt" );
    var ptmButton = `<button class="aui-buttons trigger-label" onClick="ptmTest()">Approver</button>`
    var i;
    for ( i = 0; i < x.length; i++ ) {
        if ( x[i].innerText == "Approver" ) {

            x[i].innerHTML =
                ptmButton;
            x[i].children[0].onclick = (e)=> {
                ptmTest();
            }
        }
    }

    function ptmTest() {
        console.log( "PTM clicked" )
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.