In this article, you are going to learn how to create a link (anchor element) using javascript. Suppose, you want to make a link and when someone will click on that link, he will be redirected to a new page.

There are some steps to dynamically create a link using javascript.

  1. Call the document.createElement("a") method and assign it to a variable named aTag .
  2. Then assign some text to the anchor <a> element with aTag.innerHTML property which will display as a link .
  3. Set the title and href property of the <a> element with the help of aTag.title="" and aTag.href="" .
  4. Finally, append the created <a> element to the body tag using document.body.appendChild() method.
aTag is the name of the variable.
Create an anchor tag dynamically
let aTag = document.createElement('a');
    aTag.innerHTML="I am a link";
    aTag.href="https://www.3schools.in";
    aTag.title="3schools";
    document.body.appendChild(aTag);
Try it Yourself »
You can also use the setAttribute() method instead of href="" property to set the link address. To open the link in a new tab, include the target attribute to the <a> tag and set its value to _blank.
<script>
let aTag = document.createElement('a');
    aTag.innerHTML = 'I am a link';
    aTag.setAttribute('href','http://www.3schools.in');
    aTag.setAttribute('target', '_blank');
    document.body.appendChild(aTag);
</script>

Append the <a> element inside a div element.

You can add the created anchor (<a>) element anywhere you want.

Append anchor element to a div dynamically
let divContainer = document.getElementById("container");
let aTag = document.createElement('a');
    aTag.innerHTML = 'I am a link';
    aTag.setAttribute('href', 'http://www.3schools.in');
    divContainer.appendChild(aTag);
Try it Yourself »

Create anchor element using write() method.

Example using write() method
  document.write('I am a link');
Try it Yourself »