Explain Codes LogoExplain Codes Logo

How to change the href attribute for a hyperlink using jQuery

javascript
jquery
javascript-advanced
performance
Alex KataevbyAlex Kataev·Dec 29, 2024
TLDR

To swiftly modify a hyperlink's URL with jQuery's .attr(), apply this:

$('#linkId').attr('href', 'https://newdestination.com');

Remember #linkId should be the ID of your anchor tag and https://newdestination.com is your intended link.

Changing href attributes is nuanced and needs specificity:

  • Modifying all hyperlinks:

    // Changing all hyperlinks to my personal AI fan club because, why not? $("a").attr("href", "https://aidomain.com");
  • Selecting hyperlinks with existing href:

    // If they don't have an old home, they don't get a new one! $("a[href]").attr("href", "https://aidomain.com");
  • Targeting hyperlinks with specific href:

    // Because Google needs more visitors, right? $("a[href='http://www.google.com/']").attr('href', 'https://aidomain.com');

Harnessing the power of Regular Expressions

When your hyperlinks share a common pattern, regex provides control:

// Stackoverflow becomes Stackunderflow, let's flow to a new domain $("a[href^='http://stackoverflow.com']").each(function() { this.href = this.href.replace(/^http:\/\/stackoverflow\.com/, "https://aidomain.com"); });

Prevention before the cure: Dealing with global updates

Changing all hrefs may lead to unexpected issues. Balance specificity with global updating to deliver a superior user experience.

Advanced topics

Dynamic href updates using logic

// Listen! Every single link whisper is heard... $("a.dynamic-link").on('click', function() { $(this).attr("href", fetchUrlFromMagicHat()); });

With this enjoyable snippet, every click event on an anchor with class dynamic-link sets the href to the URL returned from fetchUrlFromMagicHat(). Just like magic!

Watch out for caveats

Unusual scenarios to look out for:

  • Event handlers causing infinite loops when you set the href of the clicked link.
  • Confusion with static hrefs assigned in your HTML.
  • Internet browsers caching old hrefs causing display issues.

Performance enhancements

  • Use .prop() for boolean attributes. It's faster.
  • Cache your jQuery selectors to increase performance.
    // I can remember this for you wholesale var $links = $('a');