Change href JavaScript | Code to change URL

Use document.getElementById to Change href of anchor tag with JavaScript.

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

Change href JavaScript Example

Dynamically updating anchor tag href value in JavaScript.

<!DOCTYPE HTML>
<html>

<body>
	<a id="myLinkId" href="abc.com" >Auto update href</a>

	<script>
		var findlink = document.getElementById("myLinkId");
		findlink.href = "xyz.com";
	</script>

</html>

Output:

Change href JavaScript

How to change the href attribute value of a tag through JavaScript on a button click?

Same as above code use inside function. Add one button for perform a click. Use onclick attribute inside a button tag.

<!DOCTYPE HTML>
<html>

<body>
	<a id="myLinkId" href="abc.com" >Update href</a>

	<button onclick="updateURL()">Click</button>

	<script>
		function updateURL(){
		var findlink = document.getElementById("myLinkId");
		findlink.href = "xyz.com";
		}
	</script>

</html>

How can I add the href attribute to a link dynamically using JavaScript?

Add a href attribute to dynamically.

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

Do comment if you have any doubts and suggestion on this JS href topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.