How to select all anchor tags that contain image tags with jQuery

Turns out jQuery has the handy has selector for just this case.

Here’s a simple example that sets the title attribute of every <a> tag that contains an <img> tag and then attaches Fancybox, a lightbox-esque, image-enlargement plugin:

$("a:has(img)").attr("title", "Click to enlarge").fancybox();

I liked this approach because it meant I didn’t have to remember to add a class (e.g. class="fancybox") to every <a> tag that linked to an image I wanted to enlarge. In fact, I didn’t have to do anything special at all. Brilliant!

And then I realized I had a problem. In a few instances on my blog, I used an image (like a Firefox or Ubuntu logo) to link to an external website. Even though a:has(img) was awesome in its expressive simplicity, it turned out to be a little overzealous in those instances.

What I really wanted was something slightly more specific: the ability to attach Fancybox to <a> tags that only linked to images. But how could I determine if I was linking to an image or not? How about by the file extension.

So I used the “attribute ends with” selector combined with the multiple selector to apply Fancybox to only those <a> tags that have href attributes that end with .jpg, .png, or .gif:

$("a[href$='.jpg'],a[href$='.png'],a[href$='.gif']").attr("title", "Click to enlarge").fancybox();

This had the added bonus of enabling Fancybox on the occasional bit of text I’d used to link directly to an image.

2 Comments

Just noticied this and finding it really useful, thanks! Sharing with my team.

In the end I didn’t need the :has() selector, but it’s still a pretty handy selector that’s notably absent from the CSS selectors (on which jQuery’s selector engine, Sizzle, is based). Glad you found this useful.

Care to Comment?

Or if you'd prefer to get in touch privately, please send me an email.

Name

Email (optional)

Blog (optional)