Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the href attribute for a hyperlink using jQuery

How can you change the href attribute (link target) for a hyperlink using jQuery?

like image 787
Brian Boatright Avatar asked Oct 07 '08 18:10

Brian Boatright


People also ask

How can create href link in jQuery?

JavaScript Code:ready(function(){ $('#button1'). click(function(){ $(". link"). attr('href','https://www.w3resource.com/'); }); });

What does href =# do?

Definition and Usage The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!

Can we pass variable in href?

href”, append the variable to it (Here we have used a variable named “XYZ”). Then we need to append the value to the URL. Now our URL is ready with the variable and its value appended to it. In the example below, we will append a variable named 'XYZ' and its value is 55.


1 Answers

Using

$("a").attr("href", "http://www.google.com/") 

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://www.codeproject.com/">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:

$("a[href]") //... 

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:

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

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

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

The first part selects only links where the href starts with http://stackoverflow.com. 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.

like image 74
Shog9 Avatar answered Oct 11 '22 13:10

Shog9