CLiown
CLiown

Reputation: 13853

jQuery - Replace contents of href="" with '#'

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?

Upvotes: 8

Views: 17215

Answers (3)

Wally Lawless
Wally Lawless

Reputation: 7557

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

Upvotes: 4

Sarfraz
Sarfraz

Reputation: 382919

...

$(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', '#');
});

Upvotes: 7

jAndy
jAndy

Reputation: 236202

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

Upvotes: 15

Related Questions