2

I need to create a link on button click and also click that link with same click. I am testing the approaches mentioned on

<script type="text/javascript">
function download()
{
  alert("Hello");
  var link=document.createElement("a");

  link.href="https://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using-   javascript";
document.getElementById(link).click();

// here it says "cannot click on null", means id is not link, then how can i obtain the id

alert("Hello again");

}
</script>
<button type ="button" value="Download" onClick="download();">Downloads</button>

I need this, because, on click of button, i will be making a get call, and i will receive a URL, and then i need to click the URL (Making Download button, link can vary). Is there any other way of doing this?

I refferd: How do I programmatically click a link with javascript?

and

How do I create a link using javascript?

for achieving this, but no success.

Community
  • 1
  • 1
Vivek Vardhan
  • 1,118
  • 3
  • 21
  • 44
  • 1
    you're trying to getElementById(link) but "link" is not an Id, it's an element. give the link an id then use that id to get it and click(). – nebulae Sep 26 '13 at 14:05
  • Why do you need to create and click on a link? If you already have the URL then you can just set `window.location` to that URL? – David Sep 26 '13 at 14:06

1 Answers1

8

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();
tymeJV
  • 103,943
  • 14
  • 161
  • 157