Sometimes, we want to create a link using JavaScript.
In this article, we’ll look at how to create a link using JavaScript.
How to create a link using JavaScript?
To create a link using JavaScript, we use various DOM methods.
For instance, we write
const a = document.createElement("a");
const linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
to call createElement
to create an a
element.
Then we call createTextNode
to create a text node.
Next we call a.appendChild
to append the linkText
text node to the a
element.
We set the title
attribute of the a
element by setting the a.title
property.
And we set the href
attribute of the a
element by setting the a.href
property.
Finally, we call document.body.appendChild
with a
to append a
as the last child of the body element.
Conclusion
To create a link using JavaScript, we use various DOM methods.