To change the href of a link using JavaScript, we can use the href property along with the getElementById method.
document.getElementById("link1").href = "some-url.html";
Let’s say I have the following HTML code:
<div id="div1">
<a id="link1" href="http://theprogrammingexpert.com/">Home Page</a>
</div>
To change the href of #link1 from http://theprogrammingexpert.com/ to http://theprogrammingexpert.com/category/javascript/, we will use the href property in the following JavaScript code:
document.getElementById("link1").href = "http://theprogrammingexpert.com/category/javascript/";
The above code would change the link from the home page to the JavaScript category page.
Using JavaScript to Change the href of a Link with a Click
To change the url of a link we can combine the href property with a click event.
Let’s say we have the same HTML from above.
<div id="div1">
<a id="link-1" href="#test">This link will add #test to the current URL if clicked</a>
<div id="click-me" onclick="changeLink()">Change link</div>
</div>
We have added an onclick event to the #click-me div which will run a function where we can change the link URL. We will also change the text of the new link using the textContent property.
Here is the function below that will accomplish this:
function changeLink(){
document.getElementById("link-1").href = "#different-url";
document.getElementById("link-1").textContent = "This link will add #different-url to the current URL if clicked";
};
The final code and output for this example of how to change the href of a link using the href property and JavaScript is below:
Code Output:
Full Code:
<div id="div1">
<a id="link-1" href="#test">This link will add #test to the current URL if clicked</a>
<div id="click-me" onclick="changeLink()">Change link</div>
</div>
<script>
function changeLink(){
document.getElementById("link-1").href = "#different-url";
document.getElementById("link-1").textContent = "This link will add #different-url to the current URL if clicked";
};
</script>
Hopefully this article has helped you understand how you can use JavaScript to change the href of a link.
Leave a Reply