user992731
user992731

Reputation: 3520

Filter a word in a image src with jquery

I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images.

This is my output:

<div class="product">
  <div class="image">
   <img src="mytee-red.jpg">
   <img src="mytee-blue.jpg">
   <img src="mytee-black.jpg">
   <img src="mytee-no-image.jpg">
 </div>
</div>

This is what I've tried so far but cant seem to get it working:

var keyword = "no-image";
 $(".product .image img").filter(function(index) {
    if ($(this).attr("src") == keyword) {
        $(this).remove();
    }
});

Any help would be great!!!

Upvotes: 5

Views: 3903

Answers (5)

Lix
Lix

Reputation: 47966

You could simplify this into a single command -

$(".product .image img[src*='no-image']").remove();

The jQuery attribute contains selector will help you pin-point the exact elements that you want containing the text "no-image" anywhere within the src attribute.

This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value.

Upvotes: 6

Brett Zamir
Brett Zamir

Reputation: 14345

Other answers suggest better approaches, but a demonstration of filter() could be:

var keyword = "no-image";
 $(".product .image img").filter(function(index) {
    return $(this).attr("src").match(keyword);
}).remove();

Upvotes: 3

Majid Laissi
Majid Laissi

Reputation: 19788

according to your example, you need to use match() instead of ==

var keyword = "no-image";
 $(".product .image img").filter(function(index) {
    if ($(this).attr("src").match(keyword)) {
        $(this).remove();
    }
});

Assuming that you want to remove <img src="mytee-no-image.jpg"> as it matches the keyword no-image

Upvotes: 3

Brad
Brad

Reputation: 163234

$('.product .image img[src*="no-image"]').remove();

http://api.jquery.com/attribute-contains-selector/

No regex needed.

Upvotes: 4

Robert Karl
Robert Karl

Reputation: 7816

Filter will only keep the items where the passed function returns true. Instead of trying to remove them inside the filter function, just return false.

.filter( function(index) ): Reduce the set of matched elements to those that match the selector or pass the function's test.

var keyword = "no-image";
 $(".product .image img").filter(function(index) {
    return $(this).attr("src") != keyword;
});

Upvotes: 1

Related Questions