JQuery - How to select only images that are wrapped with links?

I need to select only images wrapped in links so that I can rel = "lightbox" to the links. I tried with 2 loops, but it does not work, as it adds the rel attribute to regular links (no images).

Here's jQuery:

$('#floorplans img').each(function() { $('#floorplans a').each(function() { $(this).attr('rel','lightbox[floorplans]'); }); }); 

Thanks.

+4
source share
3 answers

a better solution might be:

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

why is it better?

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

My solution will only select the specified bindings, not images.

+3
source

You do not need to do a loop to do this (and also your outer loop is useless since you are not using it). You can use the selector to search for images within links, and then use the closest method to search for each link, and then you can let the attr method go through the result and set the attribute for all of them:

 $('#floorplans a img').closest('a').attr('rel','lightbox[floorplans]'); 
+6
source
+1
source

Source: https://habr.com/ru/post/1346360/


All Articles