8

im trying to change href with each method,

here is demo, inspect a, you'll see there is no change

html:

<a href="#/news">News</a>
<a href="#/news/detail">Detail</a>
<a href="#/sport">Sport</a>
<a href="#/sport/football">Football</a>​​​​​​​​​​​​

jQuery:

$('a').each(function() {
  $(this).attr('href').replace('#/',''); //tried to erase #/ from all hrefs
});​
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • You can't chain replace to attr like that; just get the href as a variable with attr as a getter, do the replace, and then pump it back out again with attr as a setter. (or like elclanrs, I suppose you can just do the setter all in one!). – Greg Pettit Jul 06 '12 at 20:24

3 Answers3

15

The code you posted will get the value as a string then properly replace the values but it immediately discards the result. You need to pass in the replaced value to attr. Try the following

$('a').each(function() {
  var value = $(this).attr('href');
  $(this).attr('href', value.replace('#/',''));
});​
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
6
var href = $(this).attr('href');
$(this).attr('href', href.replace('#/',''));
elclanrs
  • 92,861
  • 21
  • 134
  • 171
2

You can also check href value and make condition

<script type="text/javascript">
$('a').each(function() {
    var value = $(this).attr('href');
    if(value=='http://google.com')
    {
        $(this).attr('href', 'http://youtube.com');
    }
});​
</script>
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43