Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, how to modify [href] value?

Tags:

jquery

For example, want to modify all href value from yahoo.com to google.com

I tried:

$("[href='http://yahoo.com']").val('http://google.com');

It won't work, what is the correct way to do so?

Thanks.

like image 386
gilzero Avatar asked Dec 07 '25 07:12

gilzero


1 Answers

If you wish to replace the "yahoo.com" portion of any href with "google.com":

$("[href*='yahoo.com']").attr("href", function(i,v){
  return v.replace("yahoo.com", "google.com");
});

This works by cycling through all elements that have "yahoo.com" anywhere in their href attribute, and replacing that string with "google.com".

​<a href="http://yahoo.com">Yahoo</a>
<a href="http://www.yahoo.com">www.yahoo.com</a>
<a href="http://yahoo.com?foo">Yahoo?</a>​​​​​​​​​​​​​​​​​

Becomes

​<a href="http://google.com">Yahoo</a>
<a href="http://www.google.com">www.yahoo.com</a>
<a href="http://google.com?foo">Yahoo?</a>​​​​​​​​​​​​​​​​​
like image 124
Sampson Avatar answered Dec 12 '25 13:12

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!