Sometimes, we want to add "href" attribute to a link dynamically using JavaScript.
In this article, we’ll look at how to add "href" attribute to a link dynamically using JavaScript.
How to add "href" attribute to a link dynamically using JavaScript?
To add "href" attribute to a link dynamically using JavaScript, we call the setAttribute
method.
For instance, we write
const a = document.getElementById("link");
a.setAttribute("href", "url");
to select the link with getElementById
.
Then we call setAttribute
with href
and the URL string to set the href attribute to the URL.
Conclusion
To add "href" attribute to a link dynamically using JavaScript, we call the setAttribute
method.