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,125
  • 11
  • 54
  • 84
  • 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
  • 703,665
  • 143
  • 1,211
  • 1,438
6
var href = $(this).attr('href');
$(this).attr('href', href.replace('#/',''));
elclanrs
  • 89,567
  • 21
  • 132
  • 165
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
  • 169,393
  • 45
  • 393
  • 567
Shafiqul Islam
  • 5,372
  • 2
  • 33
  • 41