How to change the href attribute for a hyperlink using jQuery
To swiftly modify a hyperlink's URL with jQuery's .attr()
, apply this:
Remember #linkId
should be the ID of your anchor tag and https://newdestination.com
is your intended link.
Selecting the right hyperlink
Changing href attributes is nuanced and needs specificity:
-
Modifying all hyperlinks:
-
Selecting hyperlinks with existing href:
-
Targeting hyperlinks with specific href:
Harnessing the power of Regular Expressions
When your hyperlinks share a common pattern, regex provides control:
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
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.
Was this article helpful?