Sometimes, we want to create a link with JavaScript.
In this article, we’ll look at how to create a link with JavaScript.
Use the document.createElement Method
We can use the document.createElement method to create an anchor element.
For instance,. we can write:
const a = document.createElement('a');
a.setAttribute('href', 'http://example.com');
a.innerHTML = 'example';
document.body.appendChild(a);
We call document.createElement with 'a' to create an anchor element.
Then we call setAttribute with 'href' and the value of the href attribute to set the URL that the link goes to.
Next, we set the innerHTML property to set the text content of the link.
And finally, we call document.body.appendChild to append the a link to the body.
Set the document.body.innerHTML Property
Another way to add a link to the document body is to set the innerHTML property to the HTML content we want to show.
For instance, we can write:
document.body.innerHTML = `<a href="http://example.com">example</a>`;
to set the innerHTML property top a string with the code for the anchor element.
Conclusion
We can create a link with the document.createElement method or setting the innerHTML property of the element that we want the link to be in.