JQuery select image parent element a

I am trying to select an anchor tag and add a target attribute. When it is wrapped in an image with a thumbnail of class size. Does anyone know why this is not working?

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

JQuery

 $('.size-thumbnail:parent').attr('target','_blank'); 
+4
source share
5 answers

Try the following:

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

or

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

You have a value :parent back - it selects elements that are parents, not the parent of the selected element. Try instead:

 $('.size-thumbnail').parent().attr('target','_blank'); 
+3
source

Use . parent () to traverse the Dom tree

Example:

 var Link = $("img.size-thumbnail").parent(); 

And then apply methods like attr in the Link variable, for example:

 var Link = $("img.size-thumbnail").parent(); Link.attr("target","_blank"); 
+2
source

All answers here look fine, but you can do it in reverse order:

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

you can do this because nested anchor tags are not valid;) so the image is always a child of the anchor, not multiple anchors.

+1
source

This does not work :parent .

:parent means select items that are parents to other items.

You need

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

Source: https://habr.com/ru/post/1335332/


All Articles