How can you change the href for a hyperlink using jQuery?
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:
$("a")
$("a:eq(0)")
active
) : $("a.active")
profileLink
ID) : $("a#proileLink")
$("a:first")
More useful ones:
$("[href]")
$("a[href='www.stackoverflow.com']")
$("a[href!='www.stackoverflow.com']")
$("a[href*='www.stackoverflow.com']")
$("a[href^='www.stackoverflow.com']")
$("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);
});
});