Still Learning
Still Learning

Reputation: 130

How can I select all the link which have an image child

I am using the following to add a _blank target attribute to all my external links

$.expr[':'].external = function(obj) {
    return (obj.hostname != location.hostname) && obj.href.startsWith("http");
};

$('a:external').attr('target', '_blank');

Now, I would like to do similarly for all links that are parent to images.

<a href="..."><img></a>

How can I build a selector to target these instances?

Upvotes: 2

Views: 199

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To target elements which contain another specific element you can use the :has() selector:

$('a:has(img)').prop('target', '_blank');

Also, just as an aside, the :external selector logic can be made more succinct with an arrow function:

$.expr[':'].external = obj => (obj.hostname != location.hostname) && obj.href.startsWith("http");

Upvotes: 1

Related Questions