How can you change the href attribute (link target) for a hyperlink using jQuery?
How can you change the href attribute (link target) for a hyperlink using jQuery?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using
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:
…Then you probably don’t want to accidentally add
hrefattributes to them. For safety then, we can specify that our selector will only match<a>tags with an existinghrefattribute: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:This will find links where the
hrefexactly matches the stringhttp://www.google.com/. A more involved task might be matching, then updating only part of thehref: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.