4

I am having trouble changing the href attribute of my HTML code using Jquery

My HTML code is

      <div id="main-logo"><a href="http://local.winemag.com"></a></div>

I am using the following JQuery code to change my link but for some reason it's not working.

      $("#main-logo a[href]").attr('href', 'http://www.test.com/');
Mariton
  • 601
  • 2
  • 12
  • 28
  • 2
    Works for me https://jsfiddle.net/x7mnosba/ – amflare Feb 24 '17 at 22:49
  • 2
    How do you run the code that's supposed to change the `href`? Are you sure it's running after the HTML is loaded? – Barmar Feb 24 '17 at 22:53
  • 1
    Make sure your jquery code is either wrapped in a `$(document).ready(function() { ... });` or comes at the end of the `body`. – Jessie Feb 24 '17 at 23:31
  • Possible duplicate of [How to change the href for a hyperlink using jQuery](http://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery) – Erik Philips Feb 24 '17 at 23:38
  • @user2896976 Its at the bottom of my page and wrapped in `$(document).ready(function() { ... });` I'll move it to the very bottom – Mariton Feb 25 '17 at 16:13
  • @Barmar Yes I'm sure but I will double check – Mariton Feb 25 '17 at 16:15
  • @Mariton Are there any errors in the Javascript console? If you add a `console.log()` statement, do you see the message? – Barmar Feb 27 '17 at 04:43

2 Answers2

6

to get the current value of the href based on the code provided

$("#main-logo a").attr("href");

to set the href new value would be

$("#main-logo a").attr("href","http://www.test.com/");

linc
  • 104
  • 2
3

Make sure you have that line executed once the document is ready:

jQuery(document).ready(function($) {

  //
  $("#main-logo a").attr('href', 'http://www.test.com/');

});
zJorge
  • 798
  • 2
  • 13
  • 26