How to change the href for a hyperlink using jQuery

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

Text Copied From
on : Tue, Oct 07, 2008 Views : 1155856

Accepted Answer

$(a).attr(href, http:

...Will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. anchor) anchor tags:

<a name=MyLinks></a> <a href=http:
//>The CodeProject</a> 

...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute:


Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href, you might use something like this:

//']).attr('href', 'http:

This will find links where the href exactly matches the string http:
. A more involved task might be matching, then updating only part of the href:


 this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,


The first part selects only links where the href starts with http:
. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.

Text Copied From
on : Tue, Oct 07, 2008

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp