Reputation: 1527
I have an image with an ID of 27.
I need to change the href of the link that surrounds it. How do i do this with jquery?
Here is my link and image attribute. Note. I cant set the id to the link.
<a href=""><img src="" id="27"></a>
Upvotes: 0
Views: 116
Reputation: 165941
$("#27").parent().attr("href", "somewhere.html");
This gets the direct parent of the element matched by the selector. Alternatively, you could use closest
, which traverses the DOM tree until it finds a matching element, but I'm assuming that the img
will always be a direct child of the a
element.
Note, however, that id
attribute values cannot start with a number unless you are using an HTML5 doctype
.
Update
Having seen the split opinion in the many answers to this question on the use of parent()
vs. closest("a")
, I put a quick performance test together, and, in Chrome 12 at least, the parent()
method is significantly faster (over 30% faster when I ran it).
Here's a link to the test.
Upvotes: 4
Reputation: 1015
var $mylink="test_link.html";
$('#27').parent().attr('href',$mylink);
Upvotes: 0
Reputation: 7123
James answer is good.
I prefer to use closest
instead of parent
in case the design changes.
$("#27").closest("a").attr("href","infinityandbeyond.com")
Upvotes: 0
Reputation: 44376
Has any one considered
$("#27").parent().attr("href", "something.html");
Because that would work.
Upvotes: 0
Reputation: 7117
Perhaps something like:
$('#27').closest('a').attr('href','newLink.html');
Upvotes: 2
Reputation: 179046
Use the parent
selector with the attr
method.
$('#27').parent().attr('href', someNewValue);
Upvotes: 1