Search code examples
jqueryappendlabelcategoriesoverlay

How can i target an image with an a href with jquery?


I'm trying to add category labels over an a href image with jquery. Now i have the following fiddle: https://jsfiddle.net/Eddiebouncer/43x6L2bj/ The jquery checks what category is in the link and adds the label. But this also targets text-links (which was to be expected in the end).

How can i target only a href's with the image in it to overlay the label?

Regards, Ed'

HTML

<div style="padding:20px;margin-top:40px;">
  Example with 2 images with category A and B. Script generates a category-label accordingly.
</div>
<div class="relative-container">
  <a href="something/category-A/#"><img src="https://placehold.it/300x150" /></a>
</div>
<div class="relative-container">
  <a href="something/category-B/#"><img src="https://placehold.it/300x150" /></a>
</div>
<div style="padding:20px;">
  Here a text link - but this shouldn't be targeted: <a href="something/category-A/#">read more</a>
</div>

JS

$(document).ready(function() {
  $('a[href*="category-A"]').append('<div id="overlay-A">category A</div>');
  $('a[href*="category-B"]').append('<div id="overlay-B">category B</div>');
});

CSS

.relative-container {
  position: relative;
}

#overlay-A,
#overlay-B {
  display: inline block;
  position: absolute;
  top: 0;
  left: 0;
  padding: 12px;
  color: #fff;
}

#overlay-A {
  background: rgba(0, 0, 120, 0.75);
}

#overlay-B {
  background: rgba(0, 120, 0, 0.75);
}

Solution

  • Easy, use the .relative-container class to differentiate for the two

    $(document).ready(function() {
      $('.relative-container a[href*="category-A"]').append('<div id="overlay-A">category A</div>');
    
      $('.relative-container a[href*="category-B"]').append('<div id="overlay-B">category B</div>');
    });
    

    or test if the link has a image

    $('.relative-container a[href*="category-A"]').each(function() {
       if($(this).find('img').length) {
          $(this).append('<div id="overlay-B">category B</div>');
        }
    })