Cris Cris - 2 years ago 104
Javascript Question

jQuery - How to select only images that are wrapped in links?

I need to select only images wrapped in links so I can the rel="lightbox" to the links. I've tried with 2 loops but it doesn't work as it adds the rel attribute to normal links too (without images).

Here's the jQuery:

$('#floorplans img').each(function() {
$('#floorplans a').each(function() {

Thank you.

Answer Source

a better solution could be:

$('#floorplans a:has(img)').attr('rel', 'lightbox[floorplans]');

why its better?

Guffa's solution will select all the images inside anchors into a jQuery set (which can be a big overkill, if you have a large number of images in the page).

My solution will only select the specified anchors, and not the images.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download