How to create a link using JavaScript?

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 can use the createElement method.

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 with 'a' to create an anchor element.

Then we call createTextNode to create a text node.

Then we call a.appendChild with linkText to use linkText as the text content of the anchor element.

We set the title attribute by setting a.title.

The href attribute is set by setting a.href.

And finally, we call document.body.appendChild with a to append the anchor element as the last child of the body element.

Conclusion

To create a link using JavaScript, we can use the createElement method.