Approach to Create a link
To create a link programmatically, we first understand what exactly we need to do.
Create an anchor <a> tag
For creating an anchor, we can utilize the code provided below. Create an element(<a> tag) and assign it to the variable named “anchor” as we will need it later:
After creating the anchor tag, we need to write some text inside the <a> tag as demonstrated below:
Write text into the <a> tag
For writing some text inside the <a> tag, first create a text node and then append that text node as a child to the anchor tag. The code for writing text into the anchor tag will go like this:
let textNode = document.createTextNode("Linuxhint Website");
// Append the textNode as a child to anchor.
At this stage, the text is appended into the anchor <a> tag. Now, we need to put the link in the href attribute of the anchor <a> tag as shown below.
Set the href attribute of <a> tag
After setting the href attribute, the only thing left is to append the <a> tag where we want it to be put.
Append the <a> tag to HTML body
To append the anchor tag to the body, use the following line of code.
Let’s take a simple example where we will simply create a link and append it to the HTML body and will checkout the behavior of the link if it is working or not.
First, we will create a button and at the click of that button the createLink() method will be called.
let anchor = document.createElement('a');
let link = document.createTextNode("Linuxhint Website");
anchor.href = "https://linuxhint.com/";
Once everything is in order and ready to be executed, let’s verify this and run the code.
Click the button and see if it is actually creating the link for us or not.
Here in the above screen, you can see that after clicking the button, the link was created successfully and displayed on our webpage. This link has given up with the address of linuxhint.com which means if you click on it you will be directed to linuxhint.com.
Prepend the <a> tag
The only change that we need is to use “document.body.prepend” instead of “document.body.append” to prepend the anchor tag to the top of the page above every element.
As you can see above, the link was prepended on top of every HTML element and is clickable with the address attached to it.