Search code examples
javascriptbuttonclickhref

Why button.click() is not working in my script?


I have a script in JavaScript that in a part of the code create a 'virtual button' and press it automatically.

This button is not in the HTML page and is only used to store a link that at a certain point of the script must be clicked. Here's the code:

var virtualButton = document.createElement("button");
var linkText = document.createTextNode("assign to relevant user");
virtualButton.appendChild(linkText);
virtualButton.title = "assign to relevant user";
virtualButton.href = link;
document.body.appendChild(virtualButton);

virtualButton.click();

Everything seems fine to me, still the code does not actually click the button.

Am I missing something here?


Solution

  • <button/> elements do not have an .href attribute. You most likely want to use an anchor (<a/>) element. See below:

    var virtualButton = document.createElement("a");
    var linkText = document.createTextNode("assign to relevant user");
    virtualButton.appendChild(linkText);
    virtualButton.title = "assign to relevant user";
    virtualButton.href = "https://www.google.com";
    document.body.appendChild(virtualButton);
    
    virtualButton.click();

    (It won't actually navigate because it is in a sandboxed <iframe/>, but you will see it attempt to do so).