JavaScript Code


How to change URL of link element using JavaScript?


Tutorials using JS

Change URL of link element

Given a link element in the document, change URL of link element using JavaScript.

Solution

To change the URL of a link element in the document using JavaScript, select the link element by the required selection criteria, and use link element’s href property. Set href property for the link element with the required URL.

const link = document.getElementById("link1");
link.href = "/a-new-link/"; 

Program

In the following HTML code, we have a button element and a link element. When user clicks on the button, we change the URL of the link element to '/new-link/'.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Update URL of link element</h2>
<button id="myBtn">Click me</button><br>
<a id="link1" href="/old-link/">A Link</a><br>

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //get  the link
    const link = document.getElementById("link1");
    //set new URL for the link
    link.href = "/new-link/";
});
</script>

</body>
</html>

Copyright @2022