I’m having difficulty changing the ID of this link on the fly with jquery. I can change the link text, but not the ID. Any ideas?
<a href="#" id="follow-5">follow</a>
and when you click the link, i’d like for it to look like:
<a href="#" id="following-5">following</a>
here is my jquery code
$("a[id^='follow']").live('click', function(e) {
e.preventDefault();
var aid = $(this).attr('id').substring(7);
$.ajax({
type: "POST", url: "/artist/", data: "command=becomeFan&aid=" + aid,
dataType: "html",
success: function(data){
$("#follow-" + aid).text("Following");
$("#follow-" + aid).prev("a").attr("id","following-" + aid);
}
});
return false;
});
Well the problem is your code doesn’t try to change the id of that element, it tries to change the id of the
.prev()element. So change:to:
And it should work. But given you’ve already selected the same element on the line before you should just chain the
.attrcall:Or rather than reselected the element by id, save a reference to it before making the Ajax call:
Note also that your use of the attribute starts with selector with
$("a[id^='follow']")will continue to select those elements even after their id is changed, but using.substring(7)to get the id from the end will not work after you change the id. You might want to change that to$("a[id^='follow-']")so the click handler only works on the links not already clicked.