Skip to content

Change href JavaScript | Example code to change URL

  • by

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 the function. Add one button to perform a click. Use the 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 dynamically.

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

Do comment if you have any doubts and suggestions 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

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading