How do I programmatically click a link with javascript?

Viewed 477717

Is there a way to click on a link on my page using JavaScript?

12 Answers

If you only want to change the current page address, you can do that by simply doing this in Javascript :

location.href = "http://www.example.com/test";

This function works in at least Firefox, and Internet Explorer. It runs any event handlers attached to the link and loads the linked page if the event handlers don't cancel the default action.

function clickLink(link) {
    var cancelled = false;

    if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0,
            false, false, false, false,
            0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }

    if (!cancelled) {
        window.location = link.href;
    }
}

Simply like that :

<a id="myLink" onclick="alert('link click');">LINK 1</a>
<a id="myLink2" onclick="document.getElementById('myLink').click()">Click link 1</a>

or at page load :

<body onload="document.getElementById('myLink').click()">
...
<a id="myLink" onclick="alert('link click');">LINK 1</a>
...
</body>

Instead of clicking, can you forward to the URL that the click would go to using Javascript?

Maybe you could put something in the body onLoad to go where you want.

You could just redirect them to another page. Actually making it literally click a link and travel to it seems unnessacary, but I don't know the whole story.

for those wanting to click all links that have a particular text content, this would work:

for (const a of document.querySelectorAll("a")) {
  if (a.textContent.includes("<your text to be searched here>")) {
    a.click();
  }
}

reference: https://stackoverflow.com/a/42907920/2361131

You can't make the user's mouse do anything. But you have full control over what happens when an event triggers.

What you can do is do a click on body load. W3Schools has an example here.

Related