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.
$("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.