开发者

jQuery select parent a of an image

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. An开发者_运维知识库yone know why this wont work?

<a href="example"><img class="size-thumbnail" src="example"></a>

jquery

$('.size-thumbnail:parent').attr('target','_blank');


Try this:

$('a').has('img.size-thumbnail').attr('target','_blank'); 

or

$('a.has(img.size-thumbnail)').attr('target','_blank'); 


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');


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");


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.


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜