tags:

views:

309

answers:

3

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?

+9  A: 
$('a').attr('href', '#');
jAndy
Also notable: `$('a').attr('href')` actually *returns* whatever is inside the `href` attribute. jQuery has an awesome api, also: http://api.jquery.com
dclowd9901
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
+4  A: 

...

$(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
+1  A: 

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
“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
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