jQuery - Change href attr

20,495

You just need:

var oldurl = 'http://google.com';
var newurl = 'http://yahoo.com';
$('a[href="' + oldurl + '"]').attr('href', newurl);

Demo

Urls must be string and not jQuery objects and you forgot to close the square bracket.

Share:
20,495
ITSolution
Author by

ITSolution

http://itsolution.asia

Updated on May 31, 2020

Comments

  • ITSolution
    ITSolution almost 4 years

    I trying to change href via jQuery, but I don't know why it's not working...

    $(document).ready(function () {
      var oldurl = $('`http://google.com`');
      var newurl = $('`http://yahoo.com`');
    
      $('a[href="' + oldurl + '"]').attr('href', newurl);
    
      // it's not working too...
      //$('a[href="http://google.com"]').attr('href', 'http://yahoo.com');
    
      // it's not working too...
      //$('.mylink').attr('href', newurl);
    });
    

    JSFiddle