How to replace the attr href element with each? // strip url

im trying to change href with each method,

here is a demo, check, you will see that there are no changes

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 });​ 
+7
source share
3 answers

The code you enter will receive the value as a string , and then correctly replace values, but immediately cancel the result. You need to pass the replaced value to attr . Try the following

 $('a').each(function() { var value = $(this).attr('href'); $(this).attr('href', value.replace('#/','')); });​ 
+14
source
 var href = $(this).attr('href'); $(this).attr('href', href.replace('#/','')); 
+6
source

You can also check the href value and make a 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> 
+1
source

All Articles