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:


To change the href of #link1 from https://daztech.com/ to https://daztech.com/category/javascript/, we will use the href property in the following JavaScript code:


document.getElementById("link1").href = "https://daztech.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.


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:



<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.

Categorized in:

JavaScript,

Last Update: March 20, 2024