[javascript] How to change the href for a hyperlink using jQuery

How can you change the href for a hyperlink using jQuery?

This question is related to javascript html jquery hyperlink

The answer is


Stop using jQuery just for the sake of it! This is so simple with JavaScript only.

document.querySelector('#the-link').setAttribute('href', 'http://google.com');

https://jsfiddle.net/bo77f8mg/1/


Depending on whether you want to change all the identical links to something else or you want control over just the ones in a given section of the page or each one individually, you could do one of these.

Change all links to Google so they point to Google Maps:

<a href="http://www.google.com">

$("a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change links in a given section, add the container div's class to the selector. This example will change the Google link in the content, but not in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$(".content a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change individual links regardless of where they fall in the document, add an id to the link and then add that id to the selector. This example will change the second Google link in the content, but not the first one or the one in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
    <p>...second link to <a href="http://www.google.com/" 
        id="changeme">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$("a#changeme").attr('href', 
'http://maps.google.com/');

Use the attr method on your lookup. You can switch out any attribute with a new value.

$("a.mylink").attr("href", "http://cupcream.com");

Depending on whether you want to change all the identical links to something else or you want control over just the ones in a given section of the page or each one individually, you could do one of these.

Change all links to Google so they point to Google Maps:

<a href="http://www.google.com">

$("a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change links in a given section, add the container div's class to the selector. This example will change the Google link in the content, but not in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$(".content a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change individual links regardless of where they fall in the document, add an id to the link and then add that id to the selector. This example will change the second Google link in the content, but not the first one or the one in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
    <p>...second link to <a href="http://www.google.com/" 
        id="changeme">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$("a#changeme").attr('href', 
'http://maps.google.com/');

Even though the OP explicitly asked for a jQuery answer, you don't need to use jQuery for everything these days.

A few methods without jQuery:

  • If you want to change the href value of all <a> elements, select them all and then iterate through the nodelist: (example)

    var anchors = document.querySelectorAll('a');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • If you want to change the href value of all <a> elements that actually have an href attribute, select them by adding the [href] attribute selector (a[href]): (example)

    var anchors = document.querySelectorAll('a[href]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • If you want to change the href value of <a> elements that contain a specific value, for instance google.com, use the attribute selector a[href*="google.com"]: (example)

    var anchors = document.querySelectorAll('a[href*="google.com"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    

    Likewise, you can also use the other attribute selectors. For instance:

    • a[href$=".png"] could be used to select <a> elements whose href value ends with .png.

    • a[href^="https://"] could be used to select <a> elements with href values that are prefixed with https://.

  • If you want to change the href value of <a> elements that satisfy multiple conditions: (example)

    var anchors = document.querySelectorAll('a[href^="https://"], a[href$=".png"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    

..no need for regex, in most cases.


href in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:

Imagine you have this href below:

<a id="ali" alt="Ali" href="http://dezfoolian.com.au">Alireza Dezfoolian</a>

And you like to change it the link...

Using pure JavaScript without any library you can do:

document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");

But also in jQuery you can do:

$("#ali").attr("href", "https://stackoverflow.com");

or

$("#ali").prop("href", "https://stackoverflow.com");

In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the JS one...


Change the HREF of the Wordpress Avada Theme Logo Image

If you install the ShortCode Exec PHP plugin the you can create this Shortcode which I called myjavascript

?><script type="text/javascript">
jQuery(document).ready(function() {
jQuery("div.fusion-logo a").attr("href","tel:303-985-9850");
});
</script>

You can now go to Appearance/Widgets and pick one of the footer widget areas and use a text widget to add the following shortcode

[myjavascript]

The selector may change depending upon what image your using and if it's retina ready but you can always figure it out by using developers tools.


Try

link.href = 'https://...'

_x000D_
_x000D_
link.href = 'https://stackoverflow.com'
_x000D_
<a id="link" href="#">Click me</a>
_x000D_
_x000D_
_x000D_


This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.

<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>

$('.menu_link').live('click', function() {
   var thelink = $(this);
   alert ( thelink.html() );
   alert ( thelink.attr('href') );
   alert ( thelink.attr('rel') );

   return false;
});

The simple way to do so is :

Attr function (since jQuery version 1.0)

$("a").attr("href", "https://stackoverflow.com/") 

or

Prop function (since jQuery version 1.6)

$("a").prop("href", "https://stackoverflow.com/")

Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

Now, there are lot of ways to identify exact anchor or group of anchors:

Quite Simple Ones:

  1. Select anchor through tag name : $("a")
  2. Select anchor through index: $("a:eq(0)")
  3. Select anchor for specific classes (as in this class only anchors with class active) : $("a.active")
  4. Selecting anchors with specific ID (here in example profileLink ID) : $("a#proileLink")
  5. Selecting first anchor href: $("a:first")

More useful ones:

  1. Selecting all elements with href attribute : $("[href]")
  2. Selecting all anchors with specific href: $("a[href='www.stackoverflow.com']")
  3. Selecting all anchors not having specific href: $("a[href!='www.stackoverflow.com']")
  4. Selecting all anchors with href containing specific URL: $("a[href*='www.stackoverflow.com']")
  5. Selecting all anchors with href starting with specific URL: $("a[href^='www.stackoverflow.com']")
  6. Selecting all anchors with href ending with specific URL: $("a[href$='www.stackoverflow.com']")

Now, if you want to amend specific URLs, you can do that as:

For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

$("a[href^='http://www.google.com']")
   .each(function()
   { 
      this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
        return "http://proxywebsite.com/?query="+encodeURIComponent(x);
    });
   });

 $("a[href^='http://stackoverflow.com']")
   .each(function()
   { 
      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, 
         "http://stackoverflow.com");
   });

Stop using jQuery just for the sake of it! This is so simple with JavaScript only.

document.querySelector('#the-link').setAttribute('href', 'http://google.com');

https://jsfiddle.net/bo77f8mg/1/


With jQuery 1.6 and above you should use:

$("a").prop("href", "http://www.jakcms.com")

The difference between prop and attr is that attr grabs the HTML attribute whereas prop grabs the DOM property.

You can find more details in this post: .prop() vs .attr()


This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.

<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>

$('.menu_link').live('click', function() {
   var thelink = $(this);
   alert ( thelink.html() );
   alert ( thelink.attr('href') );
   alert ( thelink.attr('rel') );

   return false;
});

Try

link.href = 'https://...'

_x000D_
_x000D_
link.href = 'https://stackoverflow.com'
_x000D_
<a id="link" href="#">Click me</a>
_x000D_
_x000D_
_x000D_


Depending on whether you want to change all the identical links to something else or you want control over just the ones in a given section of the page or each one individually, you could do one of these.

Change all links to Google so they point to Google Maps:

<a href="http://www.google.com">

$("a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change links in a given section, add the container div's class to the selector. This example will change the Google link in the content, but not in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$(".content a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change individual links regardless of where they fall in the document, add an id to the link and then add that id to the selector. This example will change the second Google link in the content, but not the first one or the one in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
    <p>...second link to <a href="http://www.google.com/" 
        id="changeme">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$("a#changeme").attr('href', 
'http://maps.google.com/');

The simple way to do so is :

Attr function (since jQuery version 1.0)

$("a").attr("href", "https://stackoverflow.com/") 

or

Prop function (since jQuery version 1.6)

$("a").prop("href", "https://stackoverflow.com/")

Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

Now, there are lot of ways to identify exact anchor or group of anchors:

Quite Simple Ones:

  1. Select anchor through tag name : $("a")
  2. Select anchor through index: $("a:eq(0)")
  3. Select anchor for specific classes (as in this class only anchors with class active) : $("a.active")
  4. Selecting anchors with specific ID (here in example profileLink ID) : $("a#proileLink")
  5. Selecting first anchor href: $("a:first")

More useful ones:

  1. Selecting all elements with href attribute : $("[href]")
  2. Selecting all anchors with specific href: $("a[href='www.stackoverflow.com']")
  3. Selecting all anchors not having specific href: $("a[href!='www.stackoverflow.com']")
  4. Selecting all anchors with href containing specific URL: $("a[href*='www.stackoverflow.com']")
  5. Selecting all anchors with href starting with specific URL: $("a[href^='www.stackoverflow.com']")
  6. Selecting all anchors with href ending with specific URL: $("a[href$='www.stackoverflow.com']")

Now, if you want to amend specific URLs, you can do that as:

For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

$("a[href^='http://www.google.com']")
   .each(function()
   { 
      this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
        return "http://proxywebsite.com/?query="+encodeURIComponent(x);
    });
   });

Use the attr method on your lookup. You can switch out any attribute with a new value.

$("a.mylink").attr("href", "http://cupcream.com");

href in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:

Imagine you have this href below:

<a id="ali" alt="Ali" href="http://dezfoolian.com.au">Alireza Dezfoolian</a>

And you like to change it the link...

Using pure JavaScript without any library you can do:

document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");

But also in jQuery you can do:

$("#ali").attr("href", "https://stackoverflow.com");

or

$("#ali").prop("href", "https://stackoverflow.com");

In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the JS one...


 $("a[href^='http://stackoverflow.com']")
   .each(function()
   { 
      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, 
         "http://stackoverflow.com");
   });

Even though the OP explicitly asked for a jQuery answer, you don't need to use jQuery for everything these days.

A few methods without jQuery:

  • If you want to change the href value of all <a> elements, select them all and then iterate through the nodelist: (example)

    var anchors = document.querySelectorAll('a');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • If you want to change the href value of all <a> elements that actually have an href attribute, select them by adding the [href] attribute selector (a[href]): (example)

    var anchors = document.querySelectorAll('a[href]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • If you want to change the href value of <a> elements that contain a specific value, for instance google.com, use the attribute selector a[href*="google.com"]: (example)

    var anchors = document.querySelectorAll('a[href*="google.com"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    

    Likewise, you can also use the other attribute selectors. For instance:

    • a[href$=".png"] could be used to select <a> elements whose href value ends with .png.

    • a[href^="https://"] could be used to select <a> elements with href values that are prefixed with https://.

  • If you want to change the href value of <a> elements that satisfy multiple conditions: (example)

    var anchors = document.querySelectorAll('a[href^="https://"], a[href$=".png"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    

..no need for regex, in most cases.


Use the attr method on your lookup. You can switch out any attribute with a new value.

$("a.mylink").attr("href", "http://cupcream.com");

Depending on whether you want to change all the identical links to something else or you want control over just the ones in a given section of the page or each one individually, you could do one of these.

Change all links to Google so they point to Google Maps:

<a href="http://www.google.com">

$("a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change links in a given section, add the container div's class to the selector. This example will change the Google link in the content, but not in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$(".content a[href='http://www.google.com/']").attr('href', 
'http://maps.google.com/');

To change individual links regardless of where they fall in the document, add an id to the link and then add that id to the selector. This example will change the second Google link in the content, but not the first one or the one in the footer:

<div class="content">
    <p>...link to <a href="http://www.google.com/">Google</a>
    in the content...</p>
    <p>...second link to <a href="http://www.google.com/" 
        id="changeme">Google</a>
    in the content...</p>
</div>

<div class="footer">
    Links: <a href="http://www.google.com/">Google</a>
</div>

$("a#changeme").attr('href', 
'http://maps.google.com/');

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? Wrapping a react-router Link in an html button How to make a hyperlink in telegram without using bots? React onClick and preventDefault() link refresh/redirect? How to put a link on a button with bootstrap? How link to any local file with markdown syntax? link with target="_blank" does not open in new tab in Chrome How to create a link to another PHP page How to determine the current language of a wordpress page when using polylang? How to change link color (Bootstrap) How can I make a clickable link in an NSAttributedString?