Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.5k views
in Web Development by 5 20 37

I am trying to change URL in <a> tag by changing href attribute value through Javascript or jQuery on button click in running time

<button id="click">change link</button>

<a id="link" href="https://google.com">go to link</a>

In the above code, I need to change the href of HTML a tag when I click on the button in running time, How can I do that?


1 Answer

0 like 0 dislike
by 5 20 37
selected by
 
Best answer

How to Change href link using JavaScript?

You have URL but you want to change it to new URL by clicking some button. Or without having href attribute or you don't put a href attribute value on <a> tag, and add new href attribute.

So you can use the below JS code to change link in <a> tag using JavaScript in running time.

<button onclick="changeURL()">change link</button>
<a href="https://google.com" id="link">go to link</a>

<script>
   function changeURL(){
        var newURL = "https://youtube.com";
        document.getElementById("link").href = newURL;
    }
</script>

How to Change href link in A tag using jQuery?

<button id="click">change link</button>
<a id="link" href="https://google.com">go to link</a>
   
<script>
    $("#click").click(function(){
        $("#link").attr("href", newURL);
    });
</script>

See Also How to replace string in current URL with JavaScript?

If you don’t ask, the answer is always NO!
...