Search code examples
javascriptjqueryhtmlhref

Replacing a href link using jQuery .attr


I'm trying to change the content of a href using jQuery. I've found a number of good answers on this site, and am trying to use this one to implement it:

How to change the href for a hyperlink using jQuery

I have it wrapped in an if statement like this:

if(window.location.href == "http://test.com/Home.aspx"){

    $("a[href='https://www.surveymonkey.com/s/tester123']").attr('href', 'https://www.surveymonkey.com/s/tester234');
}

I've put some console logs in place and they show that this line of code is being reached, and that this:

$("a[href='https://www.surveymonkey.com/s/tester123']")

Is returning the correct link. However the href value is never replaced when I check the page source.

I'm using http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js?build=7111092

I'm a bit stuck on how to debug what the issue is, can anyone help spot it? Hopefully its just a stupid mistake!

--EDIT--

I have now also checked it using inspect element and it's not been replaced unfortunately.

Also thanks to @Vohuman and @roxxypoxxy for the info on not being able to see the change unless I hovered over it. Stupidly I was expecting it to work like a find/replace!


Solution

  • I think it is a Jquery version issue. You are using Jquery 1.5. In Jquery docs they have mentioned this

    Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior.

    Source https://api.jquery.com/attr/

    So try to use higher JQuery version or use .prop() instead of .attr()