Sometimes, we want to pass JavaScript variable to link.
In this article, we’ll look at how to pass JavaScript variable to link.
How to pass JavaScript variable to link?
To pass JavaScript variable to link, we use the setAttribute method.
For instance, we write
<a id="link2"> ... </a>
to add a link.
Then we write
const strLink = "2.html";
document.getElementById("link2").setAttribute("href", strLink);
to select the link with getElementById.
And then we call setAttribute with 'href' and the value of the href attribute to set the value of the href attribute.
Conclusion
To pass JavaScript variable to link, we use the setAttribute method.