Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

css

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() {
        $(this).attr('rel','lightbox[floorplans]'); 
    });
});

Thank you.

like image 250
Cris Avatar asked Dec 27 '22 22:12

Cris


2 Answers

You don't need to loop to do that (and also, your outer loop is useless as you don't use it's result in any way). You can use a selector to find images inside links, then use the closest method to find each link, and then you can let the attr method loop through the result and set the attribute on all of them:

$('#floorplans a img').closest('a').attr('rel','lightbox[floorplans]');
like image 71
Guffa Avatar answered Jan 04 '23 23:01

Guffa


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.

like image 29
yoavmatchulsky Avatar answered Jan 04 '23 23:01

yoavmatchulsky