Reputation: 59355
I am trying to select the anchor tag and add a target attribute. When it is wrapped in a image with the class size-thumbnail. Anyone know why this wont work?
<a href="example"><img class="size-thumbnail" src="example"></a>
jquery
$('.size-thumbnail:parent').attr('target','_blank');
Upvotes: 4
Views: 7246
Reputation: 21864
All answers here seem ok,but you can do it in reverse:
$('a:has(.size-thumbnail)').attr("target","_blank");
you can do that since nested anchor tags are not valid ;) so the image is always a child in an anchor and not in multiple anchors.
Upvotes: 1
Reputation: 56572
You have the meaning of :parent
backwards — it selects elements which are parents, not the parent of the selected element. Try this instead:
$('.size-thumbnail').parent().attr('target','_blank');
Upvotes: 3
Reputation: 195982
That is not how the :parent
works.
The :parent
means select elements that are parents to other elements..
You need
$('.size-thumbnail').parent().attr('target','_blank');
Upvotes: 0
Reputation: 82903
Try this:
$('a').has('img.size-thumbnail').attr('target','_blank');
or
$('a.has(img.size-thumbnail)').attr('target','_blank');
Upvotes: 5
Reputation: 57268
Use the .parent() to traverse up the Dom Tree
Example:
var Link = $("img.size-thumbnail").parent();
And then apply the methods such as attr
on the Link
variable like so:
var Link = $("img.size-thumbnail").parent();
Link.attr("target","_blank");
Upvotes: 2