How to Programmatically Click a Link with JavaScript

How to click on a link using javascript

You're clicking on the div, which has no effect. You need to click on the a.

Replace nextlink[0].click() with nextlink[0].lastElementChild.click() and it should work.

Demo (replaced link targets with alerts):

var nextlink = document.getElementsByClassName('next-previous');nextlink[0].lastElementChild.click();
<div class="next-previous">    <a href="javascript:alert('Previous')">Previous </a>        <a href="javascript:alert('Next')">Next</a>        </div>

Create a link and click it on a single button click

It seems you really just want to change the location of the page, and not actually append a link at all:

location.href = 'your link you got back'

If you actually want a physical link to be added on the page:

var link=document.createElement("a");
link.id = 'someLink'; //give it an ID!
link.href="http://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using- javascript";

//Add the link somewhere, an appendChild statement will do.
//Then run this
document.getElementById('someLink').click();


Related Topics



Leave a reply



Submit