22

Possible Duplicate:
How to change the href for a hyperlink using jQuery

I have this link:

<a id="myLink_33" href="javascript:toggleMe(1);">Toggle</a>

How can I change the href attribute of this link using Javascript/jquery so the link becomes this:

<a id="myLink_33" href="javascript:toggleMe(0);">Toggle</a>
Community
  • 1
  • 1
Ali
  • 261,656
  • 265
  • 575
  • 769

3 Answers3

35
$("#myLink_33").attr("href", "javascript:toggleMe(0);");
Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
6

In my experience changing the attributes using an id selector will not update the actual element.
However using the class and other selectors will work. So

$('#myLink_33').attr('href','http://www.google.com')

will change the value of the href attribute only when queried, but when the link is actually selected, it will default to the href value it possessed when the page loaded.

However assuming the anchor had a class="myLink_33", the attr change,

$('.myLink_33').attr('href','http://www.google.com')

would work as expected.

mac
  • 42,153
  • 26
  • 121
  • 131
Softy
  • 61
  • 1
  • 1
5

That will certainly work, however I'd like to propose an alternative.

HTML

<a class="toggle">Toggle</a>

jQuery/JavaScript

$(document).ready(function(){
  $('a.toggle').click(function (eventObject){
    var target = $(eventObject.target);

    // will add or remove the class automatically
    target.toggleClass('toggle_on');

    if(target.hasClass('toggle_on')){
      /* toggle on code here */
      alert('Toggle On');
    }
    else{
      /* toggle off code here */
      alert('Toggle Off');
    }
  });
});

This gets you out of having to use the href attribute for the toggles and lets you control things through styling and whatnot. Though my experience with jQuery is not all that extensive something like this seems a bit more conventional.

Crazy Joe Malloy
  • 834
  • 6
  • 14