8

I need a way of replacing the text contained within <a href="this text" using jQuery, I want to replace what ever text is held within quotes to a '#'.

Any suggestions?

CLiown
  • 13,665
  • 48
  • 124
  • 205

3 Answers3

15
$('a').attr('href', '#');
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • 6
    Also notable: `$('a').attr('href')` actually *returns* whatever is inside the `href` attribute. jQuery has an awesome api, also: http://api.jquery.com – dclowd9901 May 19 '10 at 14:24
  • 6
    Be aware that this sample code will replace the `href` value of **all** links on your page, which is possibly not what the OP wants to do. To narrow it down to a single element, use an ID selector instead - `$('#myLink').attr('href', '#');`. – Andy E May 19 '10 at 14:31
7

...

$(function(){
 $('a').attr('href', '#');
});

The ready handler should take care of changing the href of your links when the page loads.

If you have link(s) with some class or id set to them, you can simply do:

$(function(){
 $('a.link_class').attr('href', '#');
 // $('#some_id').attr('href', '#'); // for id
});

If you want to do it with some button click, etc, you can do like:

$('#button_id').click(function(){
  $('a').attr('href', '#');
});
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
4

This would be the simplest method:

$('a').attr('href', '#');

However if you have multiple tags on your page you'll probably want an ID so you can single out a specific one to replace.

<a id='replaceme' href='...'></a>

If there's only a subset you want to rewrite, assign a class to them.

<a class='replaceme2' href='...'></a>
<a class='replaceme2' href='...'></a>

Then you could do the following:

$('#replaceme').attr('href', '#');  
//This will only replace the href for a single link

Or

$('.replaceme2').attr('href', '#');
//This will replace the href for all links with the replaceme2 class
Wally Lawless
  • 7,539
  • 7
  • 37
  • 53
  • 1
    “However if you have multiple tags on your page you'll probably want an ID so you can single it out.” IDs are supposed to be unique. Use `class`es instead. – Mathias Bynens May 19 '10 at 14:29
  • That is exactly what I meant and why I gave the additional example of using classes. I've updated the text of the answer to hopefully read more clearly. – Wally Lawless May 19 '10 at 20:13