user11745771
user11745771

Reputation:

How to change the URL of a link using JavaScript?

I need to know how to change the url of a link.

For example www.sitename.com to www.anothersitename.com

How do i do this using javascript?

<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<button onclick="myFunction()">Change link</button>

function myFunction() {
//For example How to change Microsoft url to w3 schools url?
//what do i put here?
}

Upvotes: 0

Views: 1877

Answers (1)

messerbill
messerbill

Reputation: 5639

function changeHref() {
  document.getElementById("myAnchor").setAttribute("href", "www.google.com")
}

this will set the href attribute of your link to google.com. Of course this URL must not be hardcoded and can be replaced with a function parameter.

Upvotes: 4

Related Questions